GitCorner

Code

ossartcraftvectorcraft๐ŸŒ
2bc41aeb8602
use super::labels::{PreviousLabel, label_field, name_field, take_previous_label};
use super::panel_chrome::{
    alt_down_in_field, chevron_cell, entry_to_focus, keep_enter_in_presets, open_presets_from_keys, presets_open, return_focus_from_presets,
};
use super::text::{
    after_shift_enter, focus_field, recessed_text, select_all, select_all_on_focus, shift_enter_keeps_focus, take_armed_focus, take_dialog_focus,
};
use super::{ArmedWheelField, WheelStream, WheelStreamOwner};
use super::{CornerRadius, RangeInclusive, Rect, Response, Sense, Stroke, StrokeKind, Tokens, Ui, Unit, id_with, pos2, scrub, vec2};

/// Preferences โ€บ Units โ€บ Numbers Without Units Are Points (#394; on until set): the app sets it
/// when the preference changes (`prefs_dialog::apply_runtime`), the length fields read it.
pub(crate) fn set_bare_numbers_are_points(ctx: &egui::Context, on: bool) {
    ctx.data_mut(|d| d.insert_temp(egui::Id::unique("bare_numbers_are_points"), on));
}

/// The unit a number typed with no unit into a field in `unit` is read in: `unit`, or for a field
/// in picas points with Numbers Without Units Are Points on (where `12` could be either). A typed
/// unit (`12 mm`, `2p6`, `1in`) always wins.
pub(crate) fn typed_unit(ctx: &egui::Context, unit: Unit) -> Unit {
    let bare_points = ctx.data(|d| d.get_temp::<bool>(egui::Id::unique("bare_numbers_are_points"))).unwrap_or(true);
    if bare_points && unit == Unit::Picas { Unit::Points } else { unit }
}

pub(super) use vectorcraft_doc::decimal_point;

/// A recessed numeric field showing `value` (points) in `unit`. Returns the new value (points)
/// when the user commits (Enter / focus loss / Shift+Enter, which keeps the focus outside dialogs).
/// Supports unit suffixes and arithmetic; a number without a unit is in `unit` ([`typed_unit`]: in
/// points in a picas field with Numbers Without Units Are Points on).
pub fn num_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, unit: Unit, width: f32) -> Option<f64> {
    num_field_named(ui, id, None, value, unit, width)
}

/// [`num_field`] whose value is clamped to `bounds` (points).
pub fn num_field_within(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    bounds: RangeInclusive<f64>,
) -> Option<f64> {
    let label = take_previous_label(ui);
    unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false, "")
}

/// [`num_field_within`] that refuses a value typed outside `bounds` (points), as it refuses text
/// that doesn't read: the field flashes, keeps its value and holds the dialog open. โ†‘/โ†“, the wheel
/// and a scrub still stop at the ends.
pub fn num_field_refusing(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    bounds: RangeInclusive<f64>,
) -> Option<f64> {
    let label = take_previous_label(ui);
    unit_field_from(ui, id, label, None, value, unit, width, false, bounds, &[], false, None, "", true)
}

/// [`num_field_within`] whose empty value reads `empty` (Transform Each's Absolute scales read
/// "Mixed" when the selected objects differ): typing replaces it, as it replaces the value shown.
pub fn num_field_within_empty(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    value: Option<f64>,
    empty: &str,
    unit: Unit,
    width: f32,
    bounds: RangeInclusive<f64>,
) -> Option<f64> {
    let label = take_previous_label(ui);
    unit_field(ui, id, label, None, value, unit, width, false, bounds, &[], false, empty)
}

/// [`num_field`] for a row whose visible label is not an adjacent label widget (a grid cell with
/// its label painted separately): screen readers name the field `name` (already translated).
pub fn num_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str>, value: Option<f64>, unit: Unit, width: f32) -> Option<f64> {
    let label = take_previous_label(ui);
    unit_field(ui, id, label, name, value, unit, width, false, ANY, &[], false, "")
}

/// The field returns valid typed distances immediately and preserves the text being edited.
pub fn num_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, unit: Unit, width: f32) -> Option<f64> {
    let label = take_previous_label(ui);
    unit_field(ui, id, label, None, value, unit, width, false, ANY, &[], true, "")
}

/// Any number: the bounds of a field that has none.
pub(crate) const ANY: RangeInclusive<f64> = f64::NEG_INFINITY..=f64::INFINITY;

/// `v` within `bounds` (bounds the wrong way round or not numbers don't panic, as `f64::clamp` would).
fn within(v: f64, bounds: &RangeInclusive<f64>) -> f64 {
    v.max(*bounds.start()).min(*bounds.end())
}

/// [`num_field`]; with `share_of_value` a percentage typed alone is that share of `value`
/// ([`share_of`]). โ†‘/โ†“, the wheel and a scrub stop at `bounds` (points), and the field shows where
/// they stopped. A plain โ†‘/โ†“ or wheel step also stops at each of `stops` (points; see
/// [`step_through`]).
#[allow(clippy::too_many_arguments)]
fn unit_field(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    label: Option<PreviousLabel>,
    name: Option<&str>,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    share_of_value: bool,
    bounds: RangeInclusive<f64>,
    stops: &[f64],
    live: bool,
    empty: &str,
) -> Option<f64> {
    unit_field_from(ui, id, label, name, value, unit, width, share_of_value, bounds, stops, live, None, empty, false)
}

/// [`unit_field`] whose blank field (`value` is `None`) steps from `blank_from` (points) with
/// โ†‘/โ†“ and the wheel instead of doing nothing. With `refuse_outside`, a value typed outside
/// `bounds` is refused as text that doesn't read is, rather than kept at the nearer end. Armed
/// with id salt `id` ([`arm_field_focus`]), it takes the keyboard focus with its value selected.
#[allow(clippy::too_many_arguments)]
fn unit_field_from(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    label: Option<PreviousLabel>,
    name: Option<&str>,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    share_of_value: bool,
    bounds: RangeInclusive<f64>,
    stops: &[f64],
    live: bool,
    blank_from: Option<f64>,
    empty: &str,
    refuse_outside: bool,
) -> Option<f64> {
    let armed = take_armed_focus(ui, &id);
    let id = id_with(ui.scope_id(), id);
    let shown = value.map(|v| unit.format(v)).unwrap_or_else(|| empty.to_string());
    take_dialog_focus(ui, id, &shown);
    if armed {
        focus_field(ui, id, &shown);
    }
    let (mut buf, commit, resp, rect) = recessed_text(ui, id, &shown, width, 1, label, name);
    if armed {
        // A field armed while it has focus keeps the text typed into it: select all of that text.
        select_all(ui, id, &buf);
    }
    select_all_on_focus(ui, &resp, &buf);
    // โ†‘/โ†“ and the wheel step in the field's unit; a drag on its label scrubs it.
    let typed = typed_unit(ui.ctx(), unit);
    let read = |b: &str| typed.parse(&decimal_point(b));
    let bounds_unit = unit.from_pt(*bounds.start())..=unit.from_pt(*bounds.end());
    let stops: Vec<f64> = stops.iter().map(|&s| unit.from_pt(s)).collect();
    let blank_from = blank_from.filter(|_| value.is_none());
    let read_unit = |b: &str| match read(b) {
        Some(v) => Some(unit.from_pt(v)),
        None if b.trim().is_empty() => blank_from.map(|v| unit.from_pt(v)),
        None => None,
    };
    let stepped = step_value(ui, &resp, &mut buf, &bounds_unit, (read_unit, |v| unit.format(unit.to_pt(v))), None, &stops);
    let scrubbed = scrub::field(ui, id, rect, &buf, value.map(|v| unit.from_pt(v)), STEP_DECIMALS, &bounds_unit);
    let commit = commit && buf != shown;
    if commit {
        let typed_value = read(&buf).or_else(|| if share_of_value { share_of(&buf, value?) } else { None });
        // A refused value is one outside `bounds` that the field doesn't show as an end: the end
        // shown in the field's unit ("352.7778 mm" for 1000 pt) reads back as that end.
        let typed_value = typed_value.filter(|&v| !refuse_outside || bounds.contains(&v) || unit.format(within(v, &bounds)) == unit.format(v));
        match typed_value {
            Some(v) => {
                let clamped = within(v, &bounds);
                let formatted = unit.format(clamped);
                ui.data_mut(|d| d.insert_temp(id, formatted));
                Some(clamped)
            }
            None => {
                let end = ui.input(|i| i.time + 0.25);
                ui.data_mut(|d| {
                    d.remove::<String>(id);
                    d.insert_temp(id.with("invalid-flash"), end);
                });
                crate::widgets::reject_dialog_commit(ui.ctx());
                ui.ctx().request_repaint();
                None
            }
        }
    } else {
        ui.data_mut(|d| d.insert_temp(id, buf.clone()));
        if let Some(v) = stepped.or(scrubbed) {
            return Some(unit.to_pt(v));
        }
        if live
            && resp.changed()
            && let Some(v) = read(&buf).filter(|v| v.is_finite()).map(|v| within(v, &bounds)).filter(|v| Some(*v) != value)
        {
            ui.data_mut(|d| d.insert_temp(id.with("shown"), unit.format(v)));
            ui.ctx().request_repaint();
            return Some(v);
        }
        None
    }
}

/// A percentage typed alone (`50%`, `150 %`, `100/3%`) as that share of `value`; `None` for any
/// other text. `Unit::parse` reads a bare percentage as nothing, having no value to take it of. A
/// decimal comma is read ([`decimal_point`]) after the `%` is dropped, so `12,5%` is 12.5% and
/// `1,000%` is refused as thousands rather than read as 1%.
pub(super) fn share_of(text: &str, value: f64) -> Option<f64> {
    let percent = vectorcraft_doc::parse_number(&decimal_point(text.trim().strip_suffix('%')?))?;
    Some(value * percent / 100.0)
}

/// The places a stepped value in a unit field keeps (no 12.300000001).
pub(super) const STEP_DECIMALS: i32 = 3;

/// `v` rounded to `decimals` places.
pub(crate) fn round_to(v: f64, decimals: i32) -> f64 {
    let scale = 10f64.powi(decimals.clamp(0, 6));
    (v * scale).round() / scale
}

/// One step of a numeric field with each modifier, most specific first (a plain pattern would also
/// match Shift): ten with Shift, a tenth with Ctrl/Cmd, else one. A Ctrl/Cmd or plain step goes to
/// the next multiple of its size ([`step_to_multiple`]); a Shift step adds or takes ten.
pub(super) const STEPS: [(egui::Modifiers, f64); 3] = [(egui::Modifiers::SHIFT, 10.0), (egui::Modifiers::COMMAND, 0.1), (egui::Modifiers::NONE, 1.0)];

/// `v` moved `n` steps of `size` (down when `n` is negative): the first step goes to the next
/// multiple of `size` in its direction and each further step adds or takes one `size`. By 1, 5.1
/// goes up to 6 and down to 5, and 5 goes up to 6 and down to 4. A value within a millionth of a
/// step of a multiple counts as that multiple.
pub(super) fn step_to_multiple(v: f64, size: f64, n: f64) -> f64 {
    if n == 0.0 {
        return v;
    }
    let q = v / size;
    let from = if n > 0.0 { (q + 1e-6).floor() } else { (q - 1e-6).ceil() };
    (from + n) * size
}

/// `v` moved `n` steps of `size` (down when negative), where each step goes to the nearer of the
/// next multiple of `size` ([`step_to_multiple`]) and the next of `stops` in its direction. By 1 with
/// stops at 0.25, 0.5 and 0.75, 0.52 goes down to 0.5 and up to 0.75, 1 goes down to 0.75, and 14
/// goes up to 15. A stop or multiple that `same` finds equal to the value counts as reached: a
/// stop shown with the same text as the value (`0.167 p` for 2 pt, see [`shown_alike`]) moves on
/// to the next.
pub(super) fn step_through(v: f64, size: f64, n: f64, stops: &[f64], same: impl Fn(f64, f64) -> bool) -> f64 {
    let mut v = v;
    // One call takes at most 1,000 steps.
    for _ in 0..n.abs().min(1000.0) as u32 {
        let mut multiple = step_to_multiple(v, size, n.signum());
        if same(multiple, v) {
            multiple = step_to_multiple(multiple, size, n.signum());
        }
        let ahead = |s: f64| (if n > 0.0 { s > v } else { s < v }) && !same(s, v);
        let stop = stops.iter().copied().filter(|&s| ahead(s));
        v = if n > 0.0 { stop.fold(multiple, f64::min) } else { stop.fold(multiple, f64::max) };
    }
    v
}

/// Whether `a` and `b` are within a millionth of `size` of each other.
#[cfg(test)]
pub(super) fn within_a_millionth(size: f64) -> impl Fn(f64, f64) -> bool {
    move |a, b| (a - b).abs() <= size.abs() * 1e-6
}

/// Whether `show` gives `a` and `b` the same text, for [`step_through`]: the field's โ†‘/โ†“ and the
/// spinner both treat a stop shown as the value as reached.
pub(super) fn shown_alike(show: impl Fn(f64) -> String) -> impl Fn(f64, f64) -> bool {
    move |a, b| show(a) == show(b)
}

/// โ†‘/โ†“ in focused numeric field `resp`, or the mouse wheel turned over it, step the number `buf`
/// shows (`read` parses it, `show` formats it) per press or wheel notch ([`STEPS`]): a plain step
/// goes to the next whole number in its direction (5.1 up to 6, down to 5), a Ctrl/Cmd step goes to
/// the next tenth, and a Shift step adds or takes ten. Steps stop at the field's `bounds` (#3370:
/// a weight stops at 0, a miter limit at 1), and a plain step also stops at each of `stops`
/// ([`step_through`]). The new value is applied at once, and
/// the new text replaces `buf`, all selected so typing
/// replaces it when focused. Returns the new number when a step was taken. An enabled field takes
/// the wheel without taking keyboard focus, and the panel under it doesn't scroll, when the wheel
/// stream began over the field and the pointer was moved onto it, or pressed on it, after the
/// field last moved or was covered ([`number_wheel_turns`]). Arrow keys still require keyboard focus.
fn step_value(
    ui: &Ui,
    resp: &Response,
    buf: &mut String,
    bounds: &RangeInclusive<f64>,
    (read, show): (impl Fn(&str) -> Option<f64>, impl Fn(f64) -> String),
    step: Option<fn(f64, f64) -> f64>,
    stops: &[f64],
) -> Option<f64> {
    // Memory focus, as the field's highlight and its typing use: `Response::has_focus` also needs the
    // window to report keyboard focus.
    if !resp.enabled() {
        return None;
    }
    let focused = ui.memory(|m| m.has_focus(resp.id));
    use egui::{Event, Key, MouseWheelUnit};
    let (taken, owns) = number_wheel_turns(ui, resp);
    let wheel = !taken.is_empty();
    let hold = wheel || owns && resp.contains_pointer();
    if !focused && !hold {
        return None;
    }
    // Wheel turns in notches: a line each, or `line` points of a trackpad or a fine wheel; what is
    // left of a notch carries over to the next turn.
    let (options, notch_id) = (ui.ctx().options(|o| o.input_options), resp.id.with("wheel"));
    let line = options.line_scroll_speed;
    let mut notches: f32 = if wheel { ui.data(|d| d.get_temp(notch_id)).unwrap_or(0.0) } else { 0.0 };
    let tail_key = wheel_tail_id(ui.ctx().viewport_id());
    let mut tail: WheelTail = if wheel { ui.data(|d| d.get_temp(tail_key)).unwrap_or_default() } else { WheelTail::default() };
    let pass = ui.ctx().cumulative_pass_nr();
    let stored: Option<(u64, Vec<(Event, egui::Vec2)>)> = if wheel { ui.data(|d| d.get_temp(wheel_turns_id(tail_key))) } else { None };
    let mut measured = stored.filter(|(at, _)| *at == pass).map(|(_, turns)| turns);
    let mut turns = Vec::new();
    let mut took = egui::Vec2::ZERO;
    // Each press and each turn of whole notches in the order they came: its modifiers and size from
    // [`STEPS`], and how many steps up (down when negative).
    let mut steps: Vec<(egui::Modifiers, f64, f64)> = Vec::new();
    let mut taken = taken;
    ui.input_mut(|i| {
        let (page, dt) = (i.viewport_rect().height(), i.stable_dt);
        // In a pass [`WheelTailPlugin`] did not run in (it is added in this one), the field
        // measures the pass's turns itself.
        turns = match measured.take() {
            Some(turns) => turns,
            None if wheel => wheel_turns(&mut tail, &i.events, &options, page, i.time),
            None => Vec::new(),
        };
        i.events.retain(|e| {
            // Each taken event is matched once by its value, so wheel events that other code adds
            // or removes before the field runs do not shift which events the field takes.
            let mine = taken.iter().position(|t| t == e).map(|at| taken.swap_remove(at)).is_some();
            let (Event::Key { modifiers, .. } | Event::MouseWheel { modifiers, .. }) = e else { return true };
            let Some(&(mods, size)) = STEPS.iter().find(|(m, _)| modifiers.matches_logically(*m)) else { return true };
            let n = match e {
                Event::Key { key: Key::ArrowUp, pressed: true, .. } if focused => 1.0,
                Event::Key { key: Key::ArrowDown, pressed: true, .. } if focused => -1.0,
                Event::MouseWheel { unit, delta, phase, .. } if mine => {
                    if *phase == egui::TouchPhase::Move {
                        // Each turn of the pass was measured in the order egui read them; a turn
                        // other code added after that falls back on the touch state.
                        took += match turns.iter().position(|(t, _)| t == e) {
                            Some(at) => turns.remove(at).1,
                            None => unsmoothed_points(&options, page, tail.touch, *unit, *delta, *modifiers),
                        };
                    }
                    // Shift may turn the wheel sideways (the Mac does).
                    let d = if modifiers.shift { delta.x + delta.y } else { delta.y };
                    notches += match unit {
                        MouseWheelUnit::Point => d / line.max(1.0),
                        MouseWheelUnit::Line | MouseWheelUnit::Page => d,
                    };
                    let whole = notches.trunc();
                    notches -= whole;
                    f64::from(whole)
                }
                _ => return true,
            };
            if n != 0.0 {
                steps.push((mods, size, n));
            }
            false
        });
        if hold {
            // The rest of a turn egui spreads over the next frames scrolls nothing either.
            i.smooth_scroll_delta = egui::Vec2::ZERO;
        }
        // What egui has not let out of the turns taken here yet stays out of scrolling after the
        // pointer leaves the field ([`WheelTailPlugin`]).
        tail.owed += took - tail_release(took, dt);
    });
    if wheel {
        ui.data_mut(|d| {
            d.insert_temp(notch_id, notches);
            d.insert_temp(tail_key, tail);
            d.insert_temp(wheel_turns_id(tail_key), (pass, turns));
        });
    }
    if steps.is_empty() {
        return None;
    }
    let mut v = read(buf)?;
    for (mods, size, n) in steps {
        v = match step {
            // The field's own steps: ten at once with Shift, one with or without Ctrl/Cmd.
            Some(step) => step(v, if mods == egui::Modifiers::SHIFT { 10.0 * n } else { n }),
            None if mods == egui::Modifiers::SHIFT => v + size * n,
            None if mods == egui::Modifiers::NONE && !stops.is_empty() => step_through(v, size, n, stops, shown_alike(&show)),
            None => step_to_multiple(v, size, n),
        };
        // Each step stops at the bounds, so a step back in the same frame starts from there.
        v = within(v, bounds);
    }
    // Rounded as fields show it, within the field's bounds; a stop keeps its places (0.0156 in).
    let v = within(if stops.contains(&v) { v } else { round_to(v, STEP_DECIMALS) }, bounds);
    *buf = show(v);
    ui.data_mut(|d| d.insert_temp(resp.id, buf.clone()));
    if focused {
        select_all(ui, resp.id, buf);
    }
    Some(v)
}

/// An enabled number field as the wheel finds it.
#[derive(Clone, Copy)]
struct WheelTarget {
    id: egui::Id,
    rect: Rect,
    layer: egui::LayerId,
}

/// Where the pointer was, the field it was last moved onto, and the running wheel stream.
#[derive(Clone, Copy, Default)]
struct WheelWalk {
    pointer: Option<egui::Pos2>,
    armed: Option<ArmedWheelField>,
    stream: WheelStream,
}

/// The number fields' wheel state in one viewport.
#[derive(Clone, Default)]
struct NumberWheel {
    /// The pass whose events `walk` and `taken` cover.
    pass: Option<u64>,
    /// The enabled number fields drawn in the pass before `pass`.
    before: Vec<WheelTarget>,
    /// The enabled number fields drawn so far in `pass`.
    drawn: Vec<WheelTarget>,
    walk: WheelWalk,
    /// Each wheel event of `pass` that a field takes, with the field.
    taken: Vec<(egui::Id, egui::Event)>,
}

/// The wheel events of this pass that number field `resp` takes, and whether the field holds the
/// wheel stream after them. The first field drawn in a pass reads the pass's events for every
/// field, using where the fields were drawn in the pass before. A field takes a wheel stream only
/// when the stream begins with the pointer over it and the pointer was moved onto it, or pressed
/// on it, after the field last moved or was covered by a window or overlay. A stream that began
/// anywhere else stays there until it ends ([`WheelStream`]) or the pointer is pressed on a field,
/// and a stream that leaves its field does not return to it. Trackpad momentum never starts a
/// stream on a field.
fn number_wheel_turns(ui: &Ui, resp: &Response) -> (Vec<egui::Event>, bool) {
    let ctx = ui.ctx();
    let key = egui::Id::unique("number-field-wheel").with(ctx.viewport_id());
    let pass = ctx.cumulative_pass_nr();
    let font_key = super::taken_from_raw_id(ctx.viewport_id());
    let fresh = ui.data_mut(|d| {
        let state = d.get_temp_mut_or_default::<NumberWheel>(key);
        if state.pass == Some(pass) {
            return None;
        }
        let follows = state.pass.is_some_and(|last| last + 1 == pass);
        state.before = if follows { std::mem::take(&mut state.drawn) } else { Vec::new() };
        state.drawn.clear();
        state.pass = Some(pass);
        if !follows {
            state.walk.pointer = None;
            state.walk.armed = None;
            state.walk.stream.release_any();
        }
        // Turns the font family field took from the raw input belong to its stream.
        let font_took = d.remove_temp::<f64>(font_key);
        let state = d.get_temp_mut_or_default::<NumberWheel>(key);
        if let Some(at) = font_took {
            state.walk.stream.note_taken_elsewhere(at);
        }
        // A field that missed a pass may have moved.
        if let Some(armed) = state.walk.armed
            && !state.before.iter().any(|t| t.id == armed.id)
        {
            state.walk.armed = None;
            state.walk.stream.release(armed.id);
        }
        Some((state.walk, state.before.clone()))
    });
    let walked = fresh.map(|(walk, before)| {
        if ctx.with_plugin(|_: &mut WheelTailPlugin| ()).is_none() {
            ctx.add_plugin(WheelTailPlugin);
        }
        let (events, now) = ui.input(|i| (i.events.clone(), i.time));
        walk_wheel(ctx, walk, &events, &before, now, pass)
    });
    let target = WheelTarget { id: resp.id, rect: resp.interact_rect, layer: resp.layer_id };
    let (armed_here, pointer) = ui.data_mut(|d| {
        let state = d.get_temp_mut_or_default::<NumberWheel>(key);
        if let Some((walk, taken)) = walked {
            state.walk = walk;
            state.taken = taken;
        }
        (state.walk.armed.is_some_and(|armed| armed.id == resp.id), state.walk.pointer)
    });
    // A window or overlay over the pointer covers the armed field even when no input arrives.
    let covered = armed_here && pointer.is_some_and(|p| target.rect.contains(p) && ctx.layer_id_at(p) != Some(target.layer));
    ui.data_mut(|d| {
        let state = d.get_temp_mut_or_default::<NumberWheel>(key);
        if let Some(armed) = &mut state.walk.armed
            && armed.id == resp.id
        {
            if armed.rect == target.rect && !covered {
                armed.pass = pass;
            } else {
                // The field moved or is covered, so the pass's turns stay with the panel.
                state.walk.armed = None;
                state.walk.stream.release(resp.id);
                state.taken.retain(|&(id, _)| id != resp.id);
            }
        }
        state.drawn.push(target);
        let mut mine = Vec::new();
        state.taken.retain(|(id, event)| {
            if *id == resp.id {
                mine.push(event.clone());
            }
            *id != resp.id
        });
        (mine, state.walk.stream.owner == Some(WheelStreamOwner::Field(resp.id)))
    })
}

/// `walk` after `events`, with `fields` where the pointer finds them, at input time `now`; and the
/// wheel events a field takes (see [`NumberWheel::taken`]).
fn walk_wheel(
    ctx: &egui::Context,
    mut walk: WheelWalk,
    events: &[egui::Event],
    fields: &[WheelTarget],
    now: f64,
    pass: u64,
) -> (WheelWalk, Vec<(egui::Id, egui::Event)>) {
    let under = |p: Option<egui::Pos2>| {
        let p = p?;
        let layer = ctx.layer_id_at(p);
        fields.iter().rev().find(|t| t.rect.contains(p) && layer == Some(t.layer)).copied()
    };
    let mut taken = Vec::new();
    let mut left = false;
    for event in events {
        match event {
            egui::Event::PointerMoved(p) | egui::Event::PointerButton { pos: p, .. } => {
                let pressed = matches!(event, egui::Event::PointerButton { pressed: true, .. });
                if walk.pointer != Some(*p) || pressed {
                    let field = under(Some(*p));
                    walk.armed = field.map(|t| ArmedWheelField { id: t.id, rect: t.rect, pass });
                    if let Some(WheelStreamOwner::Field(id)) = walk.stream.owner
                        && field.is_none_or(|t| t.id != id)
                    {
                        walk.stream.release(id);
                    }
                    // A press on a field gives it the rest of a running stream.
                    if pressed
                        && let Some(t) = field
                        && walk.stream.owner != Some(WheelStreamOwner::Field(t.id))
                    {
                        walk.stream.owner = None;
                    }
                }
                walk.pointer = Some(*p);
            }
            egui::Event::PointerGone => {
                walk.pointer = None;
                walk.armed = None;
                walk.stream.release_any();
            }
            egui::Event::MouseWheel { delta, source, .. } => {
                walk.stream.note_input(now);
                let field = under(walk.pointer);
                if *delta != egui::Vec2::ZERO {
                    let starts = field
                        .filter(|t| walk.armed.is_some_and(|armed| armed.id == t.id) && *source != egui::MouseWheelSource::Momentum)
                        .map_or(WheelStreamOwner::Elsewhere, |t| WheelStreamOwner::Field(t.id));
                    let owner = *walk.stream.owner.get_or_insert(starts);
                    if field.is_none_or(|t| owner != WheelStreamOwner::Field(t.id)) {
                        walk.stream.owner = Some(WheelStreamOwner::Elsewhere);
                    }
                }
                if let Some(t) = field
                    && walk.stream.owner == Some(WheelStreamOwner::Field(t.id))
                {
                    taken.push((t.id, event.clone()));
                } else {
                    left |= *delta != egui::Vec2::ZERO;
                }
            }
            _ => {}
        }
    }
    // egui smooths a pass's wheel input as a whole before any field runs, so a field cannot take
    // part of it: a pass whose wheel input also scrolls something else is left whole to the panel.
    if left {
        taken.clear();
    }
    (walk, taken)
}

/// The wheel turns that number fields took in one viewport and egui has not let out yet (points),
/// whether a trackpad touch is running there, and the time and source of the last wheel event.
#[derive(Clone, Copy, Default)]
struct WheelTail {
    owed: egui::Vec2,
    touch: bool,
    last: f64,
    trackpad: bool,
}

impl WheelTail {
    /// Ends a touch that egui ends at `time` because no wheel event came for a while (its
    /// `WheelState::is_scroll_action_over`): 1 s for a trackpad, 0.15 s for any other source.
    fn expire_touch(&mut self, time: f64) {
        let timeout = if self.trackpad { 1.0 } else { 0.150 };
        if self.touch && timeout < time - self.last {
            self.touch = false;
        }
    }
}

fn wheel_tail_id(viewport: egui::ViewportId) -> egui::Id {
    egui::Id::unique("number-field-wheel-tail").with(viewport)
}

/// Where the wheel turns of a pass are kept with their [`unsmoothed_points`] and the pass number,
/// from [`wheel_turns`].
fn wheel_turns_id(tail: egui::Id) -> egui::Id {
    tail.with("turns")
}

/// Reads the wheel events of a pass at `time` in order, as egui does, into `tail`'s touch state
/// (a start begins a touch; an end or cancel ends it and drops what is owed; a touch with no event
/// for a while ends), and returns each turn with its [`unsmoothed_points`] at that point.
fn wheel_turns(tail: &mut WheelTail, events: &[egui::Event], options: &egui::InputOptions, page: f32, time: f64) -> Vec<(egui::Event, egui::Vec2)> {
    let mut turns = Vec::new();
    for event in events {
        if let egui::Event::MouseWheel { unit, delta, phase, modifiers, source } = event {
            tail.expire_touch(time);
            tail.last = time;
            tail.trackpad = *source == egui::MouseWheelSource::Trackpad;
            match phase {
                egui::TouchPhase::Start => tail.touch = true,
                egui::TouchPhase::End | egui::TouchPhase::Cancel => {
                    tail.touch = false;
                    tail.owed = egui::Vec2::ZERO;
                    // egui drops what the pass's earlier turns left as well.
                    turns.iter_mut().for_each(|(_, points)| *points = egui::Vec2::ZERO);
                }
                egui::TouchPhase::Move => turns.push((event.clone(), unsmoothed_points(options, page, tail.touch, *unit, *delta, *modifiers))),
            }
        }
    }
    tail.expire_touch(time);
    turns
}

/// The points of wheel turn `delta` in `unit` that egui spreads over the next passes instead of
/// scrolling at once (its `WheelState::on_wheel_event`): a turn sideways with the horizontal
/// scroll modifier, up and down with the vertical one, and nothing for a zoom turn, a touch or a
/// turn under 8 points. `page` is the viewport's height. `modifiers` are the turn's own: egui keeps a
/// touch's modifiers only inside the touch, where nothing is spread out.
fn unsmoothed_points(
    options: &egui::InputOptions,
    page: f32,
    touch: bool,
    unit: egui::MouseWheelUnit,
    delta: egui::Vec2,
    modifiers: egui::Modifiers,
) -> egui::Vec2 {
    let mut d = match unit {
        egui::MouseWheelUnit::Point => delta,
        egui::MouseWheelUnit::Line => options.line_scroll_speed * delta,
        egui::MouseWheelUnit::Page => page * delta,
    };
    let (sideways, upright) = (modifiers.matches_any(options.horizontal_scroll_modifier), modifiers.matches_any(options.vertical_scroll_modifier));
    if sideways && !upright {
        d = egui::vec2(d.x + d.y, 0.0);
    }
    if upright && !sideways {
        d = egui::vec2(0.0, d.x + d.y);
    }
    let smooth = touch || unit == egui::MouseWheelUnit::Point && d.length() < 8.0;
    if smooth || modifiers.matches_any(options.zoom_modifier) { egui::Vec2::ZERO } else { d }
}

/// What egui lets out in a pass `dt` seconds long of `owed` points of wheel input it has not let
/// out yet (its `WheelState::after_events`): all of an axis under a point, otherwise the share that
/// lets out 90% in 0.1 s.
fn tail_release(owed: egui::Vec2, dt: f32) -> egui::Vec2 {
    let t = egui::emath::exponential_smooth_factor(0.90, 0.1, dt.min(0.1));
    let axis = |v: f32| if v.abs() < 1.0 { v } else { t * v };
    egui::vec2(axis(owed.x), axis(owed.y))
}

/// Takes out of each pass's scrolling what egui lets out of the wheel turns number fields took
/// ([`WheelTail`]), before any panel scrolls, so the rest of a turn a field took scrolls nothing
/// after the pointer leaves the field. A turn's end or cancel drops what is left. It also measures
/// each wheel turn of the pass with the touch state egui had at that turn, for [`step_value`].
#[derive(Default)]
struct WheelTailPlugin;

impl egui::Plugin for WheelTailPlugin {
    fn debug_name(&self) -> &'static str {
        "number field wheel tail"
    }

    fn on_begin_pass(&mut self, ui: &mut Ui) {
        let key = wheel_tail_id(ui.ctx().viewport_id());
        let (options, pass) = (ui.ctx().options(|o| o.input_options), ui.ctx().cumulative_pass_nr());
        let mut tail = ui.data(|d| d.get_temp::<WheelTail>(key)).unwrap_or_default();
        let mut turns = Vec::new();
        ui.input_mut(|i| {
            turns = wheel_turns(&mut tail, &i.events, &options, i.viewport_rect().height(), i.time);
            if tail.owed == egui::Vec2::ZERO {
                return;
            }
            let release = tail_release(tail.owed, i.stable_dt);
            tail.owed -= release;
            // A zoom turn takes what egui lets out, so nothing of it reaches scrolling.
            if i.smooth_scroll_delta != egui::Vec2::ZERO || i.zoom_delta() == 1.0 {
                i.smooth_scroll_delta -= release;
            }
        });
        ui.data_mut(|d| {
            d.insert_temp(key, tail);
            d.insert_temp(wheel_turns_id(key), (pass, turns));
        });
    }
}

/// A [`num_field`] for a width or height (Transform panel, Properties panel, Control bar): Ctrl/Cmd+Enter
/// also commits it and ends its editing, as Enter does, and [`enter_modifiers`] reports Command. A
/// percentage typed alone (`50%`) is that share of the size shown (#2401).
pub fn size_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, unit: Unit, width: f32) -> Option<f64> {
    size_field_named(ui, id, None, value, unit, width)
}

/// [`size_field`] for a row named explicitly instead of by an adjacent label widget.
pub fn size_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str>, value: Option<f64>, unit: Unit, width: f32) -> Option<f64> {
    use egui::{Event, Key};
    let label = take_previous_label(ui);
    // The text box does not end its editing on an Enter with Ctrl/Cmd: a plain Enter goes in right
    // after it, so the box first takes the text typed before it in this frame.
    let field = id_with(ui.scope_id(), &id);
    if ui.memory(|m| m.has_focus(field)) {
        ui.input_mut(|i| {
            let cmd_enter = |e: &Event| matches!(e, Event::Key { key: Key::Enter, pressed: true, modifiers, .. } if modifiers.command);
            if let Some(at) = i.events.iter().position(cmd_enter) {
                let enter = Event::Key { key: Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
                i.events.insert(at + 1, enter);
            }
        });
    }
    unit_field(ui, id, label, name, value, unit, width, true, ANY, &[], false, "")
}

/// [`plain_field`] for a number kept within `range` (the values of dialogs, preferences and panels
/// such as the Stroke panel's Limit); `None` shows a blank field, as [`mixed_field`] does. What is
/// typed, stepped or scrubbed is clamped into it and rounded to `decimals` places (0: a count), and
/// โ†‘/โ†“, the wheel and a scrub stop at its ends in the field too (#3370).
pub fn range_field(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    value: impl Into<Option<f64>>,
    range: RangeInclusive<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
) -> Option<f64> {
    range_field_named(ui, id, None, value, range, suffix, decimals, width)
}

/// [`range_field`] for a row named explicitly instead of by an adjacent label widget.
#[allow(clippy::too_many_arguments)]
pub fn range_field_named(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    name: Option<&str>,
    value: impl Into<Option<f64>>,
    range: RangeInclusive<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
) -> Option<f64> {
    let places = decimals.min(6) as i32;
    let value = value.into().map(|v| within(v, &range));
    let label = take_previous_label(ui);
    bounded_field(ui, id, label, name, value, suffix, decimals, width, &range, None, false, false).map(|v| within(round_to(v, places), &range))
}

/// The field returns valid typed values immediately within `range` and preserves incomplete input.
pub fn range_field_live(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    value: impl Into<Option<f64>>,
    range: RangeInclusive<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
) -> Option<f64> {
    let value = value.into().map(|v| within(v, &range));
    let label = take_previous_label(ui);
    let field = id_with(ui.scope_id(), &id);
    let result = bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, None, false, true)
        .map(|v| within(round_to(v, decimals.min(6) as i32), &range));
    if let Some(value) = result {
        ui.data_mut(|d| d.insert_temp(field.with("shown"), field_text(value, suffix, decimals)));
    }
    result
}

/// The field returns valid typed numbers immediately and preserves the text being edited.
pub fn plain_field_live(ui: &mut Ui, id: impl std::hash::Hash, value: f64, suffix: &str, decimals: usize, width: f32) -> Option<f64> {
    let label = take_previous_label(ui);
    bounded_field(ui, id, label, None, Some(value), suffix, decimals, width, &ANY, None, false, true)
}

/// [`range_field`] whose โ†‘/โ†“ and wheel take `step`'s steps instead of whole numbers (see
/// [`SliderValue::step`]), for a number whose useful values are fractions, such as the Pencil's
/// Fidelity.
#[allow(clippy::too_many_arguments)]
pub fn range_field_stepped(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    value: impl Into<Option<f64>>,
    range: RangeInclusive<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
    step: fn(f64, f64) -> f64,
) -> Option<f64> {
    let places = decimals.min(6) as i32;
    let value = value.into().map(|v| within(v, &range));
    let label = take_previous_label(ui);
    bounded_field(ui, id, label, None, value, suffix, decimals, width, &range, Some(step), false, false).map(|v| within(round_to(v, places), &range))
}

/// [`plain_field`] for a value the selected objects may not share: `None` shows a blank field.
pub fn mixed_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, suffix: &str, decimals: usize, width: f32) -> Option<f64> {
    mixed_field_named(ui, id, None, value, suffix, decimals, width)
}

/// [`mixed_field`] for a row named explicitly instead of by an adjacent label widget.
pub fn mixed_field_named(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    name: Option<&str>,
    value: Option<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
) -> Option<f64> {
    let label = take_previous_label(ui);
    bounded_field(ui, id, label, name, value, suffix, decimals, width, &ANY, None, false, false)
}

/// [`bounded_field_reading`] that reads one pair of parentheses around its text only while it shows
/// its value in parentheses.
#[allow(clippy::too_many_arguments)]
fn bounded_field(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    label: Option<PreviousLabel>,
    name: Option<&str>,
    value: Option<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
    bounds: &RangeInclusive<f64>,
    step: Option<fn(f64, f64) -> f64>,
    parentheses: bool,
    live: bool,
) -> Option<f64> {
    bounded_field_reading(ui, id, label, name, value, suffix, decimals, width, bounds, step, parentheses, parentheses, live)
}

/// [`mixed_field`] whose โ†‘/โ†“, wheel and scrub stop at `bounds`; โ†‘/โ†“ and the wheel take `step`'s steps
/// when it is given (see [`SliderValue::step`]). Armed with id salt `id` ([`arm_field_focus`]), it
/// takes the keyboard focus with its value selected. With `parentheses` it shows its value as
/// `(12)`; with `read_parentheses` it reads typed text as [`field_number`] does with its Kerning flag.
#[allow(clippy::too_many_arguments)]
fn bounded_field_reading(
    ui: &mut Ui,
    id: impl std::hash::Hash,
    label: Option<PreviousLabel>,
    name: Option<&str>,
    value: Option<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
    bounds: &RangeInclusive<f64>,
    step: Option<fn(f64, f64) -> f64>,
    parentheses: bool,
    read_parentheses: bool,
    live: bool,
) -> Option<f64> {
    let armed = take_armed_focus(ui, &id);
    let id = id_with(ui.scope_id(), id);
    let show = |value: f64| field_text(value, suffix, decimals);
    let read = |buf: &str| field_number(buf, suffix, read_parentheses);
    let shown = value.map(|v| if parentheses { format!("({})", show(v)) } else { show(v) }).unwrap_or_default();
    take_dialog_focus(ui, id, &shown);
    if armed {
        focus_field(ui, id, &shown);
    }
    let (mut buf, commit, resp, rect) = recessed_text(ui, id, &shown, width, 1, label, name);
    if armed {
        // A field armed while it has focus keeps the text typed into it: select all of that text.
        select_all(ui, id, &buf);
    }
    select_all_on_focus(ui, &resp, &buf);
    // โ†‘/โ†“ and the wheel step at the field's precision (a count ignores Ctrl/Cmd's tenth); a drag on
    // its label scrubs it.
    let decimals = decimals.min(6) as i32;
    let stepped = step_value(ui, &resp, &mut buf, bounds, (read, show), step, &[]).map(|v| round_to(v, decimals));
    let scrubbed = scrub::field(ui, id, rect, &buf, value, decimals, bounds);
    if commit && buf != shown {
        let typed = read(&buf);
        if typed.is_none() {
            // Text that reads as no number is refused as [`unit_field_from`] refuses it: the field
            // flashes, shows its value again, and an open dialog is not confirmed by this Enter.
            let end = ui.input(|i| i.time + 0.25);
            ui.data_mut(|d| {
                d.remove::<String>(id);
                d.insert_temp(id.with("invalid-flash"), end);
            });
            crate::widgets::reject_dialog_commit(ui.ctx());
            ui.ctx().request_repaint();
        }
        typed
    } else if let Some(v) = stepped.or(scrubbed).filter(|&v| Some(v) != value) {
        Some(v)
    } else if live && resp.changed() {
        read(&buf).filter(|v| v.is_finite()).map(|v| within(v, bounds)).filter(|v| Some(*v) != value).inspect(|&v| {
            ui.data_mut(|d| d.insert_temp(id.with("shown"), show(v)));
            ui.ctx().request_repaint();
        })
    } else {
        None
    }
}

/// The number text typed into a [`bounded_field`] with `suffix` reads as. The suffix, `%` and `ยฐ`
/// may follow any operand: `45*2ยฐ`, `50% / 2`. With `parentheses` (Kerning, which shows its
/// automatic value as `(12)`), one pair of parentheses around the whole text is dropped first, so
/// `(12)` reads as 12. Any other parentheses are refused: `(10+5)*2` reads as nothing, not as
/// `10+5*2`. A decimal comma is read ([`decimal_point`]) after the suffix, `%`, `ยฐ` and that pair
/// are dropped, so `(1,000)` and `1,000%` are refused as thousands rather than read as 1.
pub(super) fn field_number(buf: &str, suffix: &str, parentheses: bool) -> Option<f64> {
    let suffix = suffix.trim();
    let bare = if suffix.is_empty() { buf.to_string() } else { buf.replace(suffix, "") };
    let bare = bare.replace(['%', 'ยฐ'], "");
    let bare = bare.trim();
    let bare = if parentheses { bare.strip_prefix('(').and_then(|b| b.strip_suffix(')')).unwrap_or(bare) } else { bare };
    vectorcraft_doc::parse_number(&decimal_point(bare))
}

/// The text [`plain_field`] shows for `value`: at most `decimals` places, without trailing zeros,
/// then `suffix`.
pub(super) fn field_text(value: f64, suffix: &str, decimals: usize) -> String {
    let s = format!("{:.*}", decimals, value);
    let s = if s.contains('.') { s.trim_end_matches('0').trim_end_matches('.').to_string() } else { s };
    format!("{s}{suffix}")
}

/// A slider whose rail shows, filled up to the handle: the theme's widget fill matches the panel
/// and dialog background, which leaves only the handle visible (#1483).
pub fn slider(ui: &mut Ui, slider: egui::Slider<'_>) -> Response {
    let t = Tokens::get(ui.ctx());
    ui.scope(|ui| {
        let v = ui.visuals_mut();
        // The buttons' border shows against the panel in every brightness; the fields' border
        // all but vanished on Medium Dark's panel (#1662).
        v.widgets.inactive.bg_fill = t.button_border;
        v.selection.bg_fill = t.accent;
        ui.add(slider.trailing_fill(true))
    })
    .inner
}

/// Numeric field with an up/down spinner on the left and a preset dropdown on the right
/// (Stroke weight, font sizeโ€ฆ): an editable combo box whose field keeps typing, โ†‘/โ†“ stepping and
/// label scrubbing. `value` (points) shows in `unit`, blank when `None` (the selection's values
/// differ); `presets` (points) are listed in `unit` too, and empty = no dropdown. The spinner, โ†‘/โ†“,
/// the wheel and a scrub stop at `min` (#3370), and a typed value below it applies `min`. Returns
/// the committed, stepped or picked value.
#[allow(clippy::too_many_arguments)]
pub fn spin_field(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<f64> {
    spin_field_named(ui, id, None, value, unit, width, step, min, presets)
}

/// [`spin_field`] for a row named explicitly instead of by an adjacent label widget.
#[allow(clippy::too_many_arguments)]
pub fn spin_field_named(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    name: Option<&str>,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<f64> {
    spin_field_auto_named(ui, id, name, value, None, unit, width, step, min, presets).and_then(SpinPick::value)
}

/// [`spin_field_named`] whose plain steps (the spinner, โ†‘/โ†“ and the wheel without a modifier) also
/// stop at each of its presets ([`step_through`]), for the Stroke Weight: by 1 pt with presets at
/// 0.25, 0.5 and 0.75 pt, 0.52 pt goes down to 0.5 pt and up to 0.75 pt.
#[allow(clippy::too_many_arguments)]
pub fn spin_field_stops_named(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    name: Option<&str>,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<f64> {
    let label = take_previous_label(ui);
    let blank_from = BLANK_WEIGHT_STEPS_FROM;
    // A blank field steps in points from `blank_from`, whatever the unit's preset ladder (#5349).
    let stops = if value.is_none() { &BLANK_WEIGHT_STOPS[..] } else { presets };
    let fmt = |v: f64| unit.format(v);
    spin_generic(ui, label, value, Some(blank_from), None, None, None, width, step, min, presets, stops, &fmt, &mut |ui, fw, label| {
        unit_field_from(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, stops, false, Some(blank_from), "", false)
    })
    .and_then(SpinPick::value)
}

/// Where a blank Stroke Weight (the selected objects differ) steps from, in points: up goes to
/// 0.5 pt and down to 0 pt. This is the behaviour #5349 asks for.
const BLANK_WEIGHT_STEPS_FROM: f64 = 0.25;

/// The stops a blank Stroke Weight steps through, in points, so that up gives 0.5 pt in every
/// Units > Stroke, not the first preset of the unit's own ladder above 0.25 pt.
const BLANK_WEIGHT_STOPS: [f64; 2] = [BLANK_WEIGHT_STEPS_FROM, 0.5];

/// A distance field with spinner arrows kept within `bounds` (points), as the Drop Shadow and
/// Outer Glow dialogs show their offsets and blur: the spinner steps one `unit` at a time
/// (Shift ร—10, Ctrl/Cmd รท10), and it, โ†‘/โ†“, the wheel, a scrub and a typed value stop at both
/// ends. Returns the committed or stepped value in points.
pub fn spin_length_within(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    value: Option<f64>,
    unit: Unit,
    width: f32,
    bounds: RangeInclusive<f64>,
) -> Option<f64> {
    let label = take_previous_label(ui);
    let step = Some(unit.to_pt(1.0)).filter(|s| s.is_finite() && *s > 0.0).unwrap_or(1.0);
    let field = bounds.clone();
    spin_generic(ui, label, value, None, None, None, None, width, step, *bounds.start(), &[], &[], &|v| unit.format(v), &mut |ui, fw, label| {
        unit_field(ui, id, label, None, value, unit, fw, false, field.clone(), &[], false, "")
    })
    .and_then(SpinPick::value)
    .map(|v| within(v, &bounds))
}

/// [`range_field`] with spinner arrows (Opacity and Darkness in the Drop Shadow and Outer Glow
/// dialogs): the spinner steps by `step` (Shift ร—10, Ctrl/Cmd รท10) and, like โ†‘/โ†“, the wheel, a
/// scrub and a typed value, stops at the ends of `range`.
#[allow(clippy::too_many_arguments)]
pub fn spin_range(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    value: Option<f64>,
    range: RangeInclusive<f64>,
    suffix: &str,
    decimals: usize,
    width: f32,
    step: f64,
) -> Option<f64> {
    let label = take_previous_label(ui);
    let places = decimals.min(6) as i32;
    let value = value.map(|v| within(v, &range));
    let fmt = |v: f64| format!("{v}{suffix}");
    spin_generic(ui, label, value, None, None, None, None, width, step, *range.start(), &[], &[], &fmt, &mut |ui, fw, label| {
        bounded_field(ui, id, label, None, value, suffix, decimals, fw, &range, None, false, false)
    })
    .and_then(SpinPick::value)
    .map(|v| within(round_to(v, places), &range))
}

/// What a [`spin_field_auto`] returns: a value (points), or its Auto entry.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SpinPick {
    Value(f64),
    Auto,
    Optical,
}

impl SpinPick {
    /// The value, `None` for Auto.
    pub fn value(self) -> Option<f64> {
        match self {
            SpinPick::Value(v) => Some(v),
            SpinPick::Auto => None,
            SpinPick::Optical => None,
        }
    }
}

/// [`spin_field`] whose dropdown starts with an Auto entry (Leading): `auto` is `Some(on)`, with
/// `on` checking it (no preset is then checked), or `None` for no Auto entry.
#[allow(clippy::too_many_arguments)]
pub fn spin_field_auto(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    value: Option<f64>,
    auto: Option<bool>,
    unit: Unit,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<SpinPick> {
    spin_field_auto_named(ui, id, None, value, auto, unit, width, step, min, presets)
}

/// [`spin_field_auto`] for a row named explicitly instead of by an adjacent label widget.
#[allow(clippy::too_many_arguments)]
pub fn spin_field_auto_named(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    name: Option<&str>,
    value: Option<f64>,
    auto: Option<bool>,
    unit: Unit,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<SpinPick> {
    let label = take_previous_label(ui);
    spin_generic(ui, label, value, None, auto, None, None, width, step, min, presets, &[], &|v| unit.format(v), &mut |ui, fw, label| {
        unit_field(ui, id, label, name, value, unit, fw, false, min..=f64::INFINITY, &[], false, "")
    })
}

/// [`spin_field`] for unitless values (percent, degrees, 1/1000 em) with a display suffix; a
/// `None` value (the selection's values differ) shows blank.
#[allow(clippy::too_many_arguments)]
pub fn spin_plain(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    value: impl Into<Option<f64>>,
    suffix: &str,
    decimals: usize,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<f64> {
    spin_plain_named(ui, id, None, value, suffix, decimals, width, step, min, presets)
}

/// [`spin_plain`] for a row named explicitly instead of by an adjacent label widget.
#[allow(clippy::too_many_arguments)]
pub fn spin_plain_named(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    name: Option<&str>,
    value: impl Into<Option<f64>>,
    suffix: &str,
    decimals: usize,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
) -> Option<f64> {
    let label = take_previous_label(ui);
    let value = value.into();
    let fmt = |v: f64| format!("{v}{suffix}");
    spin_generic(ui, label, value, None, None, None, None, width, step, min, presets, &[], &fmt, &mut |ui, fw, label| {
        bounded_field(ui, id, label, name, value, suffix, decimals, fw, &(min..=f64::INFINITY), None, false, false)
    })
    .and_then(SpinPick::value)
}

/// Kerning's numeric field and automatic method choices. With `parentheses` the field shows its
/// value as `(12)`; typed text such as `(10+5)` reads with one pair of parentheses around it either
/// way.
#[allow(clippy::too_many_arguments)]
pub fn spin_kerning(
    ui: &mut Ui,
    id: impl std::hash::Hash + Copy,
    value: Option<f64>,
    automatic: Option<bool>,
    optical: Option<bool>,
    optical_label: &str,
    parentheses: bool,
    width: f32,
    presets: &[f64],
) -> Option<SpinPick> {
    let label = take_previous_label(ui);
    spin_generic(
        ui,
        label,
        value,
        None,
        automatic,
        optical,
        Some(optical_label),
        width,
        10.0,
        -1000.0,
        presets,
        &[],
        &|v| format!("{v}"),
        &mut |ui, fw, label| bounded_field_reading(ui, id, label, None, value, "", 0, fw, &(-1000.0..=f64::INFINITY), None, parentheses, true, false),
    )
}

type SpinField<'a> = dyn FnMut(&mut Ui, f32, Option<PreviousLabel>) -> Option<f64> + 'a;

#[allow(clippy::too_many_arguments)]
fn spin_generic(
    ui: &mut Ui,
    label: Option<PreviousLabel>,
    value: Option<f64>,
    blank_from: Option<f64>,
    auto: Option<bool>,
    optical: Option<bool>,
    optical_label: Option<&str>,
    width: f32,
    step: f64,
    min: f64,
    presets: &[f64],
    stops: &[f64],
    fmt: &dyn Fn(f64) -> String,
    field: &mut SpinField<'_>,
) -> Option<SpinPick> {
    let t = Tokens::get(ui.ctx());
    let mut out = None;
    let h = 26.0;
    let enabled = ui.is_enabled();
    ui.scope(|ui| {
        // The spinner, the field and the chevron share their borders: one box in three parts. The
        // spinner is not a Tab stop (โ†‘/โ†“ in the field step it), so Tab goes from field to field.
        ui.spacing_mut().item_spacing.x = -1.0;
        let (sr, sresp) = ui.allocate_exact_size(vec2(16.0, h), Sense::CLICK);
        ui.painter().rect_filled(sr, CornerRadius { nw: 2, sw: 2, ne: 0, se: 0 }, t.input);
        ui.painter().rect_stroke(sr, CornerRadius { nw: 2, sw: 2, ne: 0, se: 0 }, Stroke::new(1.0, t.input_border), StrokeKind::Inside);
        let up = Rect::from_min_max(sr.min, pos2(sr.right(), sr.center().y));
        let down = Rect::from_min_max(pos2(sr.left(), sr.center().y), sr.max);
        let hover = sresp.hover_pos();
        for (r, is_up) in [(up, true), (down, false)] {
            let c = if !enabled {
                t.text_disabled
            } else if hover.is_some_and(|p| r.contains(p)) {
                t.text_strong
            } else {
                t.icon
            };
            let m = r.center();
            let d = if is_up { -1.5 } else { 1.5 };
            ui.painter().line_segment([m + vec2(-3.0, -d), m + vec2(0.0, d)], Stroke::new(1.2, c));
            ui.painter().line_segment([m + vec2(0.0, d), m + vec2(3.0, -d)], Stroke::new(1.2, c));
        }
        sresp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, tl!("Step up or down")));
        // A blank field (values that differ) steps from `blank_from`, if any. A click steps once; an
        // arrow held down steps again and again after a pause, as a spin button does (#4267).
        let is_up = match held_repeat(ui, &sresp) {
            Some(true) => Some(ui.rect_contains_pointer(up)),
            None if sresp.clicked() => sresp.interact_pointer_pos().map(|p| up.contains(p)),
            _ => None,
        };
        if let (Some(is_up), Some(v)) = (is_up, value.or(blank_from)) {
            let modifiers = ui.input(|i| i.modifiers);
            out = Some(SpinPick::Value(spinner_step(v, step, min, is_up, modifiers, stops, fmt)));
        }
        let fw = if presets.is_empty() { width - 15.0 } else { width - 34.0 };
        let keyed = if presets.is_empty() { None } else { alt_down_in_field(ui, Rect::from_x_y_ranges(sr.right()..=sr.right() + fw, sr.y_range())) };
        if let Some(v) = field(ui, fw, label) {
            out = Some(SpinPick::Value(v.max(min)));
        }
        if !presets.is_empty() {
            let dresp = chevron_cell(ui, h);
            let keyed = open_presets_from_keys(ui, &dresp, keyed);
            let was_open = presets_open(ui, &dresp);
            egui::Popup::menu(&dresp).show(|ui| {
                ui.set_min_width(width - 10.0);
                let current = value.filter(|_| auto != Some(true));
                let mut entries: Vec<(bool, String, SpinPick)> = Vec::new();
                if let Some(on) = auto {
                    entries.push((on, tl!("Auto").to_string(), SpinPick::Auto));
                }
                if let Some(on) = optical {
                    entries.push((on, optical_label.unwrap_or_default().to_string(), SpinPick::Optical));
                }
                entries.extend(presets.iter().map(|p| (current.is_some_and(|v| (v - p).abs() < 1e-6), fmt(*p), SpinPick::Value(*p))));
                let focus = entry_to_focus(keyed, entries.iter().map(|e| e.0));
                for (i, (on, text, pick)) in entries.into_iter().enumerate() {
                    let r = ui.selectable_label(on, text);
                    if focus == Some(i) {
                        r.request_focus();
                    }
                    if r.clicked() {
                        out = Some(pick);
                        // Enter or Space on the focused entry is a click too, which the menu
                        // does not close on by itself.
                        ui.close();
                    }
                }
            });
            keep_enter_in_presets(ui, was_open);
            return_focus_from_presets(ui, &dresp);
        }
    });
    out
}

/// How long a spinner arrow is held before it repeats, and how often it repeats then, in seconds.
const REPEAT_DELAY: f64 = 0.45;
const REPEAT_EVERY: f64 = 0.06;

/// A spinner arrow (`resp`) held down. `None` until it has been held for [`REPEAT_DELAY`]: a
/// click then steps once, on release. After that, `Some(true)` on each frame it steps again
/// (every [`REPEAT_EVERY`]) and `Some(false)` on the frames between and on the release, which
/// must not step once more.
fn held_repeat(ui: &Ui, resp: &egui::Response) -> Option<bool> {
    let id = resp.id.with("repeat");
    let click_dist = ui.ctx().options(|o| o.input_options.max_click_dist);
    let (now, primary_held) = ui.input(|i| {
        let stayed = i.pointer.total_drag_delta().is_some_and(|d| d.length_sq() <= click_dist * click_dist);
        (i.time, i.focused && i.pointer.primary_down() && stayed)
    });
    let state: Option<(f64, f64, bool)> = ui.data(|d| d.get_temp(id));
    // Start from an egui press, but keep tracking it past the click timeout without taking drags from a scroll area (#6307).
    let down_here = primary_held && resp.contains_pointer() && !resp.long_touched();
    if !resp.enabled() || !down_here || (state.is_none() && !resp.is_pointer_button_down_on()) {
        ui.data_mut(|d| d.remove::<(f64, f64, bool)>(id));
        return state.filter(|(_, _, repeated)| *repeated).map(|_| false);
    }
    let (start, last, repeated) = state.unwrap_or((now, now, false));
    let due = now - start >= REPEAT_DELAY && now - last >= REPEAT_EVERY;
    ui.data_mut(|d| d.insert_temp(id, (start, if due { now } else { last }, repeated || due)));
    ui.ctx().request_repaint_after(std::time::Duration::from_millis(30));
    (repeated || due).then_some(due)
}

/// Spinner buttons follow the same modifier sizes as โ†‘/โ†“ in a focused number field:
/// Shift ร—10, Ctrl/Cmd รท10, otherwise the caller's normal step, which also stops at each of
/// `stops` ([`step_through`]). A stop that `show` writes with the same text as the value counts as
/// reached, as in the field. As with โ†‘/โ†“, a plain or Ctrl/Cmd step goes to the next multiple of its
/// size ([`step_to_multiple`]), a Shift step adds or takes ten steps, and the result is rounded to
/// [`STEP_DECIMALS`] places (#4490); a stop keeps its places.
pub(super) fn spinner_step(
    value: f64,
    step: f64,
    min: f64,
    up: bool,
    modifiers: egui::Modifiers,
    stops: &[f64],
    show: &dyn Fn(f64) -> String,
) -> f64 {
    let (mods, multiplier) = STEPS.iter().find(|(m, _)| modifiers.matches_logically(*m)).copied().unwrap_or((egui::Modifiers::NONE, 1.0));
    let size = step * multiplier;
    let n = if up { 1.0 } else { -1.0 };
    let v = if mods == egui::Modifiers::SHIFT {
        value + size * n
    } else if mods == egui::Modifiers::NONE && !stops.is_empty() {
        step_through(value, size, n, stops, shown_alike(show))
    } else {
        step_to_multiple(value, size, n)
    };
    (if stops.contains(&v) { v } else { round_to(v, STEP_DECIMALS) }).max(min)
}

/// A number field that may be empty (Stroke dash/gap): `value` (points) shows in `unit` without
/// its suffix, to fit narrow fields. Returns `Some(new)` (points) on commit (Enter, Shift+Enter or
/// focus loss, as in [`num_field`]), where `new` is `None` when the field was cleared; typed units
/// and arithmetic work as in [`num_field`]. The value is a length: โ†‘/โ†“, the wheel and a scrub stop
/// at 0.
pub fn opt_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, unit: Unit, width: f32) -> Option<Option<f64>> {
    opt_field_named(ui, id, None, value, unit, width)
}

/// [`opt_field`] for a field named explicitly instead of by an adjacent label widget (the Stroke
/// panel's dash and gap cells have their labels in a row below them).
pub fn opt_field_named(ui: &mut Ui, id: impl std::hash::Hash, name: Option<&str>, value: Option<f64>, unit: Unit, width: f32) -> Option<Option<f64>> {
    let t = Tokens::get(ui.ctx());
    let label = take_previous_label(ui);
    let id = id_with(ui.scope_id(), id);
    let shown = value.map(|v| unit.number(v)).unwrap_or_default();
    let editing = ui.memory(|m| m.has_focus(id));
    // As in `hex_field`: until the user types into it, the field shows `shown` as it is now
    // (#1692). When `shown` changes while the field has the focus and nothing has been typed into
    // it, all of the new text is selected, as on keyboard focus.
    let edited_id = id.with("edited");
    let edited = editing && ui.data_mut(|d| d.get_temp::<bool>(edited_id)).unwrap_or(false);
    let before = ui.data_mut(|d| d.get_temp::<String>(id));
    let mut buf: String = if edited { before.clone().unwrap_or_else(|| shown.clone()) } else { shown.clone() };
    let reshown = after_shift_enter(ui, id);
    if reshown || editing && !edited && before.is_some_and(|b| b != buf) {
        select_all(ui, id, &buf);
    }
    let kept = shift_enter_keeps_focus(ui, id);
    let enabled = ui.is_enabled();
    let framed = egui::Frame::NONE
        .fill(t.input)
        .stroke(Stroke::new(1.0, if editing { t.accent } else { t.input_border }))
        .corner_radius(CornerRadius::same(2))
        .inner_margin(egui::Margin::symmetric(4, 4))
        .show(ui, |ui| {
            ui.add(
                egui::TextEdit::singleline(&mut buf)
                    .id(id)
                    .frame(egui::Frame::NONE)
                    .align(egui::Align2::LEFT_CENTER)
                    .desired_width(width - 10.0)
                    .font(egui::FontId::proportional(12.5))
                    .text_color(if enabled { t.text_strong } else { t.text_disabled }),
            )
        });
    let resp = framed.inner;
    let resp = name_field(label_field(resp, label), name);
    select_all_on_focus(ui, &resp, &buf);
    // โ†‘/โ†“ and the wheel step a value (an empty field stays empty); a drag on its label scrubs it.
    let lengths = 0.0..=f64::INFINITY;
    let stepped = step_value(
        ui,
        &resp,
        &mut buf,
        &lengths,
        (|b: &str| Some(unit.from_pt(unit.parse(&decimal_point(b))?)), |v| unit.number(unit.to_pt(v))),
        None,
        &[],
    );
    let scrubbed = scrub::field(ui, id, framed.response.rect, &buf, value.map(|v| unit.from_pt(v)), STEP_DECIMALS, &lengths);
    let focused = ui.memory(|m| m.has_focus(id));
    ui.data_mut(|d| {
        d.insert_temp(id, buf.clone());
        d.insert_temp(edited_id, (edited || resp.changed()) && focused && !kept);
    });
    if (resp.lost_focus() || kept) && buf != shown {
        let s = buf.trim();
        if s.is_empty() { Some(None) } else { typed_unit(ui.ctx(), unit).parse(&decimal_point(s)).map(Some) }
    } else {
        stepped.or(scrubbed).map(|v| Some(unit.to_pt(v)))
    }
}