ferravex_render/ui/
inspector.rs

1//! Checked, borrowed authoring controls in logical screen units.
2//!
3//! Build from a fixed model snapshot. Numeric formatting/units and domain rules
4//! belong to the caller. No model reference is stored or mutated: only an
5//! [`InspectorOutcome::Accepted`] value may be applied, outside UI composition.
6//! Validation callbacks must be pure; arbitrary callback side effects cannot be
7//! rolled back. An invalid edit returns its error without changing the snapshot.
8//! Feed the error back as field copy next frame (for example `FieldState::Invalid`),
9//! or in a separate notice. Disabled, unavailable and invalid fields have distinct
10//! visible prefixes and never propose changes.
11//!
12//! [`InspectorLayout::finish`] atomically submits all commands through
13//! [`Ui::compose`], then finishes input and validates at most one fresh activation.
14//! It deliberately exposes no speculative result from inside a composition.
15//! Call once per frame after `Ui::begin`, after other UI submissions. Use
16//! [`InspectorLayout::finish_player`] for the existing remapped confirm route;
17//! do not separately finish/route that edge through another UI owner. On submit
18//! failure input is not finished: finish the restored prior UI or an explicit
19//! readable fallback yourself. The inspector is an overlay, not a modal; panels
20//! are paint-only. Route scene gestures using [`Ui::interaction`] after finish.
21//!
22//! All labels, values, units, status messages and controls are measured before
23//! insertion. At most 16 fields, eight choices per field and 8192 source bytes.
24//! Rows wrap without shrinking fonts; every control stays at least 44 units high.
25//! Too narrow/short bounds reject the entire layout with `InvalidLayout`: the
26//! caller must choose a larger panel, fewer fields or a separate readable view.
27//! There is no silent omission, implicit scroll or text-entry framework. Use
28//! bounds fully inside the viewport safe area and inherited clips; later ancestor
29//! clipping can still obscure content. Inspection exposes actual button rectangles
30//! and complete labels. Theme tokens map directly to ordinary text/button styles;
31//! retained button focus outlines keep their existing two-unit stroke.
32//!
33//! This runnable native recipe uses the real ordered touch journal, a fixed
34//! snapshot, pure domain validation and application after finish. It is synthetic
35//! native input, not a window/device playtest. Physics lab adoption and complete
36//! mass/gravity/friction validator recipes are handed off in task285's receipt.
37//!
38//! ```
39//! use ferravex_play::ui::theme::{ThemeMode, UiTheme};
40//! use ferravex_render::{Vec2, input::{host_frame, touch, touch_event},
41//!     ui::{Ui, UiError, Viewport, inspector::*}};
42//! let mut model = 1.0_f32;
43//! let mut ui = Ui::new();
44//! let viewport = Viewport::responsive([320., 480.], [0.; 4])?;
45//! let fields = [InspectorField {
46//!     id: 1, label: "MASS", display: "1.00", unit: "kg", state: FieldState::Enabled,
47//!     control: InspectorControl::Stepper { value: model, min: 0.1, max: 100.,
48//!         step: 0.25, policy: LimitPolicy::Reject, decrease: 2, increase: 3 },
49//! }];
50//! let layout = InspectorLayout::new(viewport.bounds(), &fields,
51//!     UiTheme::preset(ThemeMode::Normal))?;
52//! let rect = layout.control_rect(3).unwrap();
53//! for phase in [touch::Phase::Start, touch::Phase::End] {
54//!     touch_event(touch::Event { id: 7, phase,
55//!         position: Vec2::new(rect.min[0] + 2., rect.min[1] + 2.) });
56//! }
57//! host_frame(0., 320, 480, || -> Result<(), UiError> {
58//!     ui.begin(viewport);
59//!     let outcome = layout.finish(&mut ui, true, |change| {
60//!         // Substitute the existing physics/body validator, using a candidate copy.
61//!         match change.value {
62//!             FieldValue::Number(n) if n <= 10. => Ok(()),
63//!             _ => Err("mass exceeds this tool's authored limit"),
64//!         }
65//!     })?;
66//!     assert_eq!(model, 1.); // Nothing mutated during composition or validation.
67//!     if let InspectorOutcome::Accepted(change) = outcome {
68//!         if let FieldValue::Number(n) = change.value { model = n; }
69//!     }
70//!     assert!(ui.interaction().pointer_consumed);
71//!     ui.paint();
72//!     Ok(())
73//! })?;
74//! assert_eq!(model, 1.25);
75//! # Ok::<(), UiError>(())
76//! ```
77
78use super::text_layout::WrappedText;
79use super::{ButtonStyle, TextStyle, Ui, UiComposition, UiError, UiRect, WidgetId};
80use ferravex_play::ui::theme::{ColorRole, UiTheme};
81use std::fmt::{self, Write};
82
83/// Hard source bounds, checked before scanning field copy or choices.
84pub const MAX_INSPECTOR_FIELDS: usize = 16;
85/// Maximum options in one choice field.
86pub const MAX_INSPECTOR_CHOICES: usize = 8;
87/// Combined UTF-8 bytes, including disabled and unselected copy.
88pub const MAX_INSPECTOR_BYTES: usize = 8192;
89const MAX_CONTROLS: usize = MAX_INSPECTOR_FIELDS * MAX_INSPECTOR_CHOICES;
90const EMPTY: UiRect = UiRect {
91    min: [0.; 2],
92    size: [0.; 2],
93};
94
95/// An explicit authored policy; overflow/nonfinite arithmetic always rejects.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97pub enum LimitPolicy {
98    /// Reject an out-of-range finite candidate, without silently clamping.
99    Reject,
100    /// Clamp a finite candidate to the authored limits; unchanged endpoints are idle.
101    Clamp,
102}
103
104/// Availability and complete contextual message. Only `Enabled` permits edits.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum FieldState<'a> {
107    Enabled,
108    Disabled(&'a str),
109    Unavailable(&'a str),
110    Invalid(&'a str),
111}
112impl<'a> FieldState<'a> {
113    fn message(self) -> (&'static str, &'a str) {
114        match self {
115            Self::Enabled => ("", ""),
116            Self::Disabled(s) => ("X DISABLED: ", s),
117            Self::Unavailable(s) => ("X UNAVAILABLE: ", s),
118            Self::Invalid(s) => ("! INVALID: ", s),
119        }
120    }
121}
122
123/// Stable ID and complete single-line choice copy; disabled options stay visible.
124#[derive(Clone, Copy, Debug)]
125pub struct InspectorChoice<'a> {
126    pub id: WidgetId,
127    pub label: &'a str,
128    pub enabled: bool,
129}
130
131/// Borrowed control snapshot. Field and control IDs must all be distinct.
132///
133/// Toggle/choice composition, remapped finish, geometry queries and explicit
134/// close/reset, using the same borrowed snapshot contract as numeric fields:
135///
136/// ```
137/// use ferravex_play::ui::theme::{ThemeMode, UiTheme};
138/// use ferravex_render::{input::{host_frame, PlayerInput},
139///     ui::{Ui, UiError, Viewport, inspector::*}};
140/// let choices = [InspectorChoice { id: 12, label: "BALL", enabled: true },
141///                InspectorChoice { id: 13, label: "CRATE", enabled: false }];
142/// let fields = [
143///     InspectorField { id: 1, label: "GRAVITY", display: "ON", unit: "",
144///         state: FieldState::Enabled,
145///         control: InspectorControl::Toggle { value: true, id: 2, on: "ON", off: "OFF" } },
146///     InspectorField { id: 10, label: "SHAPE", display: "BALL", unit: "",
147///         state: FieldState::Enabled,
148///         control: InspectorControl::Choice { selected: 0, choices: &choices } },
149/// ];
150/// let viewport = Viewport::responsive([320., 600.], [0.; 4])?;
151/// let layout = InspectorLayout::new(viewport.bounds(), &fields,
152///     UiTheme::preset(ThemeMode::HighContrast))?;
153/// assert_eq!(layout.bounds(), viewport.bounds());
154/// assert!(layout.field_rect(10).is_some() && layout.control_rect(13).is_some());
155/// let mut ui = Ui::new();
156/// let mut player = PlayerInput::transient("inspector-recipe");
157/// host_frame(0., 320, 600, || -> Result<(), UiError> {
158///     player.sample(true);
159///     ui.begin(viewport);
160///     let result = layout.finish_player(&mut ui, &mut player, true,
161///         |_| Ok::<(), &'static str>(()))?;
162///     assert_eq!(result, InspectorOutcome::Idle);
163///     ui.paint();
164///     Ok(())
165/// })?;
166/// ui.cancel(); // Closing/reset cancels a live capture; next begin removes widgets.
167/// ui.begin(viewport);
168/// ui.finish(false); // Keep routing terminal gestures even with the tool closed.
169/// # Ok::<(), UiError>(())
170/// ```
171#[derive(Clone, Copy, Debug)]
172pub enum InspectorControl<'a> {
173    /// Finite limits, min <= max, finite step > 0. Enabled values must be finite
174    /// and within limits. Stepping uses f32 arithmetic; overflow and a rounded
175    /// unchanged sum reject, even under Clamp. No held-key repeat is synthesized.
176    Stepper {
177        value: f32,
178        min: f32,
179        max: f32,
180        step: f32,
181        policy: LimitPolicy,
182        decrease: WidgetId,
183        increase: WidgetId,
184    },
185    /// The current label is prefixed `[X]` or `[ ]`; both labels reserve width.
186    Toggle {
187        value: bool,
188        id: WidgetId,
189        on: &'a str,
190        off: &'a str,
191    },
192    /// A selected index into 1..=8 choices. Each choice has its own real button;
193    /// `[X]` indicates selection without relying on color. Selecting it is idle.
194    Choice {
195        selected: usize,
196        choices: &'a [InspectorChoice<'a>],
197    },
198}
199
200/// A fixed snapshot with caller-formatted value/units. Display must be nonblank;
201/// it is never parsed. Units may be empty. Multi-line field/status copy wraps.
202#[derive(Clone, Copy, Debug)]
203pub struct InspectorField<'a> {
204    pub id: WidgetId,
205    pub label: &'a str,
206    pub display: &'a str,
207    pub unit: &'a str,
208    pub state: FieldState<'a>,
209    pub control: InspectorControl<'a>,
210}
211
212/// Typed proposal values, with no references to a live model.
213#[derive(Clone, Copy, Debug, PartialEq)]
214pub enum FieldValue {
215    Number(f32),
216    Toggle(bool),
217    Choice(usize),
218}
219/// Previous snapshot value and validated proposed value, keyed by caller field ID.
220#[derive(Clone, Copy, Debug, PartialEq)]
221pub struct ValueChange {
222    pub field: WidgetId,
223    pub previous: FieldValue,
224    pub value: FieldValue,
225}
226/// Numeric rejection is separate from caller-owned domain validation.
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228pub enum InvalidEdit<E> {
229    NumericLimit,
230    NoNumericProgress,
231    Validation(E),
232}
233/// One finished activation. Apply Accepted once, then rebuild the snapshot.
234/// Idle includes disabled input, cancellation, a held gesture and unchanged choice.
235#[derive(Clone, Copy, Debug, PartialEq)]
236pub enum InspectorOutcome<E> {
237    Idle,
238    Accepted(ValueChange),
239    Invalid {
240        field: WidgetId,
241        reason: InvalidEdit<E>,
242    },
243}
244
245#[derive(Clone, Copy, Debug)]
246struct Row {
247    bounds: UiRect,
248    label: UiRect,
249    value: UiRect,
250    message: UiRect,
251}
252const EMPTY_ROW: Row = Row {
253    bounds: EMPTY,
254    label: EMPTY,
255    value: EMPTY,
256    message: EMPTY,
257};
258#[derive(Clone, Copy, Debug)]
259struct Control {
260    id: WidgetId,
261    rect: UiRect,
262    field: usize,
263    action: usize,
264}
265const EMPTY_CONTROL: Control = Control {
266    id: 0,
267    rect: EMPTY,
268    field: 0,
269    action: 0,
270};
271
272/// Immutable measured layout. No heap storage, model/controller or hidden reset
273/// state. Rebuild after any model/copy/theme/bounds change; `Ui::begin` clears old
274/// submissions, and `Ui::cancel` cancels capture when the tool closes/resets.
275#[derive(Debug)]
276pub struct InspectorLayout<'a> {
277    bounds: UiRect,
278    fields: &'a [InspectorField<'a>],
279    theme: UiTheme,
280    rows: [Row; MAX_INSPECTOR_FIELDS],
281    controls: [Control; MAX_CONTROLS],
282    count: usize,
283}
284
285impl<'a> InspectorLayout<'a> {
286    /// Validate bounded source and measure complete rows. Empty fields are valid.
287    /// Duplicate IDs return DuplicateId; source limits return Capacity; invalid
288    /// numeric specs, blank essential copy and impossible geometry return InvalidLayout.
289    pub fn new(
290        bounds: UiRect,
291        fields: &'a [InspectorField<'a>],
292        theme: UiTheme,
293    ) -> Result<Self, UiError> {
294        validate_source(fields)?;
295        checked_rect(bounds.min[0], bounds.min[1], bounds.size[0], bounds.size[1])?;
296        let mut result = Self {
297            bounds,
298            fields,
299            theme,
300            rows: [EMPTY_ROW; MAX_INSPECTOR_FIELDS],
301            controls: [EMPTY_CONTROL; MAX_CONTROLS],
302            count: 0,
303        };
304        let spacing = theme.spacing();
305        let inner = bounds.inset([spacing.inset; 4])?;
306        checked_rect(inner.min[0], inner.min[1], inner.size[0], inner.size[1])?;
307        let mut y = inner.min[1];
308        let mut copy = CopyBuffer::new();
309        for (index, field) in fields.iter().enumerate() {
310            let top = y;
311            let label = text_rect(inner, y, field.label, theme.types().label)?;
312            y = label.min[1] + label.size[1] + spacing.compact_gap;
313            value_copy(&mut copy, field)?;
314            let value = text_rect(inner, y, copy.as_str(), theme.types().body)?;
315            y = value.min[1] + value.size[1] + spacing.compact_gap;
316            let controls_top = y;
317            let mut x = inner.min[0];
318            let mut line_y = y;
319            for action in 0..control_count(field.control) {
320                control_copy(&mut copy, field.control, action)?;
321                let mut width = button_width(copy.as_str(), theme.types().body)?;
322                // Toggle reserves its larger state too, so toggling does not shift hits.
323                if let InspectorControl::Toggle { value, .. } = field.control {
324                    control_copy(&mut copy, toggle_value(field.control, !value), 0)?;
325                    width = width.max(button_width(copy.as_str(), theme.types().body)?);
326                }
327                if width > inner.size[0] {
328                    return Err(UiError::InvalidLayout);
329                }
330                if x + width > inner.min[0] + inner.size[0] {
331                    x = inner.min[0];
332                    line_y += spacing.control_height + spacing.compact_gap;
333                }
334                let rect = checked_rect(x, line_y, width, spacing.control_height)?;
335                contained(inner, rect)?;
336                let measured =
337                    WrappedText::new(copy.as_str(), rect.size[0] - 16., theme.types().body)?
338                        .measure();
339                if measured.line_count != 1 || measured.width > rect.size[0] - 16. {
340                    return Err(UiError::InvalidLayout);
341                }
342                result.controls[result.count] = Control {
343                    id: control_id(field.control, action),
344                    rect,
345                    field: index,
346                    action,
347                };
348                result.count += 1;
349                x = rect.min[0] + rect.size[0] + spacing.compact_gap;
350            }
351            y = line_y + spacing.control_height;
352            debug_assert!(y > controls_top);
353            let message = if field.state == FieldState::Enabled {
354                EMPTY
355            } else {
356                y += spacing.compact_gap;
357                status_copy(&mut copy, field.state)?;
358                let r = text_rect(inner, y, copy.as_str(), theme.types().body)?;
359                y = r.min[1] + r.size[1];
360                r
361            };
362            let row = checked_rect(inner.min[0], top, inner.size[0], y - top)?;
363            contained(inner, row)?;
364            result.rows[index] = Row {
365                bounds: row,
366                label,
367                value,
368                message,
369            };
370            y += spacing.gap;
371        }
372        Ok(result)
373    }
374
375    pub fn bounds(&self) -> UiRect {
376        self.bounds
377    }
378    /// Complete row including its label/value/status/control rows.
379    pub fn field_rect(&self, id: WidgetId) -> Option<UiRect> {
380        self.fields
381            .iter()
382            .position(|f| f.id == id)
383            .map(|i| self.rows[i].bounds)
384    }
385    /// Exact rectangle submitted to the existing button painter/hit registry.
386    pub fn control_rect(&self, id: WidgetId) -> Option<UiRect> {
387        self.controls[..self.count]
388            .iter()
389            .find(|c| c.id == id)
390            .map(|c| c.rect)
391    }
392
393    /// Submit atomically, finish built-in input, then run a pure validator once
394    /// for an actual change. All UI submission errors occur before validation.
395    pub fn finish<E>(
396        &self,
397        ui: &mut Ui,
398        enabled: bool,
399        validate: impl FnOnce(ValueChange) -> Result<(), E>,
400    ) -> Result<InspectorOutcome<E>, UiError> {
401        ui.compose(|group| self.submit(group))?;
402        ui.finish(enabled);
403        Ok(self.resolve(ui, validate))
404    }
405
406    /// Same transaction/result contract, using existing remapped confirm and
407    /// selected-pad handling. Unrelated gameplay edges remain caller/tick-owned.
408    pub fn finish_player<E>(
409        &self,
410        ui: &mut Ui,
411        player: &mut crate::input::PlayerInput,
412        enabled: bool,
413        validate: impl FnOnce(ValueChange) -> Result<(), E>,
414    ) -> Result<InspectorOutcome<E>, UiError> {
415        ui.compose(|group| self.submit(group))?;
416        ui.finish_player(player, enabled);
417        Ok(self.resolve(ui, validate))
418    }
419
420    fn submit(&self, group: &mut UiComposition<'_>) -> Result<(), UiError> {
421        let theme = self.theme;
422        group.push_clip(self.bounds)?;
423        group.panel(self.bounds, theme.color(ColorRole::Surface))?;
424        let mut copy = CopyBuffer::new();
425        for (field, row) in self.fields.iter().zip(self.rows.iter()) {
426            group.text(
427                row.label,
428                field.label,
429                text_style(theme, theme.types().label, ColorRole::MutedText),
430            )?;
431            value_copy(&mut copy, field)?;
432            group.text(
433                row.value,
434                copy.as_str(),
435                text_style(theme, theme.types().body, ColorRole::Text),
436            )?;
437            if field.state != FieldState::Enabled {
438                status_copy(&mut copy, field.state)?;
439                let role = if matches!(field.state, FieldState::Invalid(_)) {
440                    ColorRole::Danger
441                } else {
442                    ColorRole::DisabledText
443                };
444                group.text(
445                    row.message,
446                    copy.as_str(),
447                    text_style(theme, theme.types().body, role),
448                )?;
449            }
450        }
451        for c in &self.controls[..self.count] {
452            let field = &self.fields[c.field];
453            let enabled = field.state == FieldState::Enabled
454                && match field.control {
455                    InspectorControl::Choice { choices, .. } => choices[c.action].enabled,
456                    _ => true,
457                };
458            control_copy(&mut copy, field.control, c.action)?;
459            group.button(
460                c.id,
461                c.rect,
462                copy.as_str(),
463                enabled,
464                ButtonStyle {
465                    fill: theme.color(ColorRole::Surface),
466                    ink: theme.color(if enabled {
467                        ColorRole::Text
468                    } else {
469                        ColorRole::DisabledText
470                    }),
471                    focus: theme.color(ColorRole::Focus),
472                    disabled: theme.color(ColorRole::Surface),
473                    size: theme.types().body,
474                },
475            )?;
476        }
477        group.pop_clip()
478    }
479
480    fn resolve<E>(
481        &self,
482        ui: &Ui,
483        validate: impl FnOnce(ValueChange) -> Result<(), E>,
484    ) -> InspectorOutcome<E> {
485        let Some(c) = self.controls[..self.count]
486            .iter()
487            .find(|c| ui.activated(c.id))
488        else {
489            return InspectorOutcome::Idle;
490        };
491        let field = &self.fields[c.field];
492        if field.state != FieldState::Enabled {
493            return InspectorOutcome::Idle;
494        }
495        let candidate = match field.control {
496            InspectorControl::Stepper {
497                value,
498                min,
499                max,
500                step,
501                policy,
502                ..
503            } => {
504                let next = if c.action == 0 {
505                    value - step
506                } else {
507                    value + step
508                };
509                if !next.is_finite() {
510                    return invalid(field.id, InvalidEdit::NumericLimit);
511                }
512                if next == value {
513                    return invalid(field.id, InvalidEdit::NoNumericProgress);
514                }
515                let next = match policy {
516                    LimitPolicy::Reject if !(min..=max).contains(&next) => {
517                        return invalid(field.id, InvalidEdit::NumericLimit);
518                    }
519                    LimitPolicy::Clamp => next.clamp(min, max),
520                    _ => next,
521                };
522                if next == value {
523                    return InspectorOutcome::Idle;
524                }
525                (FieldValue::Number(value), FieldValue::Number(next))
526            }
527            InspectorControl::Toggle { value, .. } => {
528                (FieldValue::Toggle(value), FieldValue::Toggle(!value))
529            }
530            InspectorControl::Choice { selected, choices } => {
531                if !choices[c.action].enabled || selected == c.action {
532                    return InspectorOutcome::Idle;
533                }
534                (FieldValue::Choice(selected), FieldValue::Choice(c.action))
535            }
536        };
537        let change = ValueChange {
538            field: field.id,
539            previous: candidate.0,
540            value: candidate.1,
541        };
542        match validate(change) {
543            Ok(()) => InspectorOutcome::Accepted(change),
544            Err(error) => invalid(field.id, InvalidEdit::Validation(error)),
545        }
546    }
547}
548
549fn invalid<E>(field: WidgetId, reason: InvalidEdit<E>) -> InspectorOutcome<E> {
550    InspectorOutcome::Invalid { field, reason }
551}
552fn text_style(theme: UiTheme, size: f32, role: ColorRole) -> TextStyle {
553    TextStyle {
554        size,
555        color: theme.color(role),
556        wrap: true,
557        ..TextStyle::default()
558    }
559}
560fn checked_rect(x: f32, y: f32, w: f32, h: f32) -> Result<UiRect, UiError> {
561    let right = x + w;
562    let bottom = y + h;
563    if ![x, y, w, h, right, bottom].iter().all(|n| n.is_finite())
564        || w <= 0.
565        || h <= 0.
566        || right <= x
567        || bottom <= y
568    {
569        return Err(UiError::InvalidLayout);
570    }
571    Ok(UiRect {
572        min: [x, y],
573        size: [right - x, bottom - y],
574    })
575}
576fn contained(parent: UiRect, child: UiRect) -> Result<(), UiError> {
577    if (0..2).any(|a| {
578        child.min[a] < parent.min[a]
579            || child.min[a] + child.size[a] > parent.min[a] + parent.size[a]
580    }) {
581        return Err(UiError::InvalidLayout);
582    }
583    Ok(())
584}
585fn text_rect(inner: UiRect, y: f32, copy: &str, size: f32) -> Result<UiRect, UiError> {
586    let metrics = WrappedText::new(copy, inner.size[0], size)?.measure();
587    if metrics.width > inner.size[0] {
588        return Err(UiError::InvalidLayout);
589    }
590    let rect = checked_rect(inner.min[0], y, inner.size[0], metrics.required_height)?;
591    if rect.size[0] < metrics.width || rect.size[1] < metrics.required_height {
592        return Err(UiError::InvalidLayout);
593    }
594    Ok(rect)
595}
596fn button_width(copy: &str, size: f32) -> Result<f32, UiError> {
597    let width = WrappedText::new(copy, f32::MAX, size)?.measure().width;
598    Ok((width + 16.).ceil().max(44.) + 1.)
599}
600fn control_count(c: InspectorControl<'_>) -> usize {
601    match c {
602        InspectorControl::Stepper { .. } => 2,
603        InspectorControl::Toggle { .. } => 1,
604        InspectorControl::Choice { choices, .. } => choices.len(),
605    }
606}
607fn control_id(c: InspectorControl<'_>, action: usize) -> WidgetId {
608    match c {
609        InspectorControl::Stepper {
610            decrease, increase, ..
611        } => {
612            if action == 0 {
613                decrease
614            } else {
615                increase
616            }
617        }
618        InspectorControl::Toggle { id, .. } => id,
619        InspectorControl::Choice { choices, .. } => choices[action].id,
620    }
621}
622fn toggle_value(c: InspectorControl<'_>, value: bool) -> InspectorControl<'_> {
623    if let InspectorControl::Toggle { id, on, off, .. } = c {
624        InspectorControl::Toggle { value, id, on, off }
625    } else {
626        c
627    }
628}
629fn value_copy(out: &mut CopyBuffer, f: &InspectorField<'_>) -> Result<(), UiError> {
630    out.clear();
631    write!(
632        out,
633        "{}{}{}",
634        f.display,
635        if f.unit.is_empty() { "" } else { " " },
636        f.unit
637    )
638    .map_err(|_| UiError::Capacity)
639}
640fn status_copy(out: &mut CopyBuffer, state: FieldState<'_>) -> Result<(), UiError> {
641    out.clear();
642    let (prefix, message) = state.message();
643    write!(out, "{prefix}{message}").map_err(|_| UiError::Capacity)
644}
645fn control_copy(
646    out: &mut CopyBuffer,
647    c: InspectorControl<'_>,
648    action: usize,
649) -> Result<(), UiError> {
650    out.clear();
651    match c {
652        InspectorControl::Stepper { .. } => out.write_str(if action == 0 { "-" } else { "+" }),
653        InspectorControl::Toggle { value, on, off, .. } => write!(
654            out,
655            "{} {}",
656            if value { "[X]" } else { "[ ]" },
657            if value { on } else { off }
658        ),
659        InspectorControl::Choice { selected, choices } => write!(
660            out,
661            "{} {}",
662            if selected == action { "[X]" } else { "[ ]" },
663            choices[action].label
664        ),
665    }
666    .map_err(|_| UiError::Capacity)
667}
668fn single_line(copy: &str) -> bool {
669    !copy.trim().is_empty()
670        && !copy.chars().any(char::is_control)
671        && !copy.contains(['\u{2028}', '\u{2029}'])
672}
673fn validate_source(fields: &[InspectorField<'_>]) -> Result<(), UiError> {
674    if fields.len() > MAX_INSPECTOR_FIELDS {
675        return Err(UiError::Capacity);
676    }
677    // Lengths are bounded before source is scanned or IDs copied to stack storage.
678    let mut bytes = 0usize;
679    let mut add = |s: &str| -> Result<(), UiError> {
680        bytes = bytes.checked_add(s.len()).ok_or(UiError::Capacity)?;
681        if bytes > MAX_INSPECTOR_BYTES {
682            return Err(UiError::Capacity);
683        }
684        Ok(())
685    };
686    for f in fields {
687        add(f.label)?;
688        add(f.display)?;
689        add(f.unit)?;
690        add(f.state.message().1)?;
691        match f.control {
692            InspectorControl::Choice { choices, .. } => {
693                if choices.len() > MAX_INSPECTOR_CHOICES {
694                    return Err(UiError::Capacity);
695                }
696                for choice in choices {
697                    add(choice.label)?;
698                }
699            }
700            InspectorControl::Toggle { on, off, .. } => {
701                add(on)?;
702                add(off)?;
703            }
704            _ => {}
705        }
706    }
707    let mut ids = [0; MAX_INSPECTOR_FIELDS + MAX_CONTROLS];
708    let mut count = 0;
709    let mut id = |id| -> Result<(), UiError> {
710        if ids[..count].contains(&id) {
711            return Err(UiError::DuplicateId);
712        }
713        ids[count] = id;
714        count += 1;
715        Ok(())
716    };
717    for f in fields {
718        id(f.id)?;
719    }
720    for f in fields {
721        if f.label.trim().is_empty()
722            || f.display.trim().is_empty()
723            || (f.state != FieldState::Enabled && f.state.message().1.trim().is_empty())
724        {
725            return Err(UiError::InvalidLayout);
726        }
727        match f.control {
728            InspectorControl::Stepper {
729                value,
730                min,
731                max,
732                step,
733                ..
734            } => {
735                if ![min, max, step].iter().all(|n| n.is_finite())
736                    || min > max
737                    || step <= 0.
738                    || (f.state == FieldState::Enabled
739                        && (!value.is_finite() || !(min..=max).contains(&value)))
740                {
741                    return Err(UiError::InvalidLayout);
742                }
743            }
744            InspectorControl::Toggle { on, off, .. } if !single_line(on) || !single_line(off) => {
745                return Err(UiError::InvalidLayout);
746            }
747            InspectorControl::Choice { selected, choices }
748                if selected >= choices.len() || choices.iter().any(|c| !single_line(c.label)) =>
749            {
750                return Err(UiError::InvalidLayout);
751            }
752            _ => {}
753        }
754        for action in 0..control_count(f.control) {
755            id(control_id(f.control, action))?;
756        }
757    }
758    Ok(())
759}
760// Source limit plus small authored prefixes; no unbounded String/format! path.
761struct CopyBuffer {
762    bytes: [u8; MAX_INSPECTOR_BYTES + 32],
763    len: usize,
764}
765impl CopyBuffer {
766    fn new() -> Self {
767        Self {
768            bytes: [0; MAX_INSPECTOR_BYTES + 32],
769            len: 0,
770        }
771    }
772    fn clear(&mut self) {
773        self.len = 0;
774    }
775    fn as_str(&self) -> &str {
776        std::str::from_utf8(&self.bytes[..self.len]).expect("only UTF-8 str writes")
777    }
778}
779impl Write for CopyBuffer {
780    fn write_str(&mut self, text: &str) -> fmt::Result {
781        let end = self.len.checked_add(text.len()).ok_or(fmt::Error)?;
782        self.bytes
783            .get_mut(self.len..end)
784            .ok_or(fmt::Error)?
785            .copy_from_slice(text.as_bytes());
786        self.len = end;
787        Ok(())
788    }
789}
790
791#[cfg(test)]
792mod journey400_285 {
793    use super::*;
794    use crate::input::{
795        ActionKind, Binding, InputCode, PlayerInput, host_frame, touch, touch_event,
796    };
797    use ferravex_play::ui::theme::ThemeMode;
798
799    fn field() -> InspectorField<'static> {
800        InspectorField {
801            id: 1,
802            label: "MASS",
803            display: "1",
804            unit: "kg",
805            state: FieldState::Enabled,
806            control: InspectorControl::Stepper {
807                value: 1.,
808                min: 0.,
809                max: 10.,
810                step: 0.25,
811                policy: LimitPolicy::Reject,
812                decrease: 2,
813                increase: 3,
814            },
815        }
816    }
817    fn viewport() -> super::super::Viewport {
818        super::super::Viewport::responsive([320., 480.], [0.; 4]).unwrap()
819    }
820    fn accept(_: ValueChange) -> Result<(), ()> {
821        Ok(())
822    }
823    fn touch(phase: touch::Phase, rect: UiRect) {
824        touch_event(touch::Event {
825            id: 17,
826            phase,
827            position: crate::Vec2::from_array([rect.min[0] + 2., rect.min[1] + 2.]),
828        });
829    }
830
831    #[test]
832    fn keyboard_focus_skips_disabled_and_held_confirm_does_not_repeat() {
833        let choices = [
834            InspectorChoice {
835                id: 12,
836                label: "BALL",
837                enabled: false,
838            },
839            InspectorChoice {
840                id: 13,
841                label: "CRATE",
842                enabled: true,
843            },
844            InspectorChoice {
845                id: 14,
846                label: "COMPOUND",
847                enabled: true,
848            },
849        ];
850        let fields = [InspectorField {
851            control: InspectorControl::Choice {
852                selected: 0,
853                choices: &choices,
854            },
855            ..field()
856        }];
857        let layout = InspectorLayout::new(
858            viewport().bounds(),
859            &fields,
860            UiTheme::preset(ThemeMode::Normal),
861        )
862        .unwrap();
863        let mut ui = Ui::new();
864        ui.set_auto_focus(false);
865        // Establish focus/epoch before injecting the actual keys.
866        host_frame(0., 320, 480, || {
867            ui.begin(viewport());
868            layout.finish(&mut ui, true, accept).unwrap();
869        });
870        assert_eq!(ui.focused(), None);
871        crate::key(0xff09, true);
872        crate::key(0xff09, false);
873        crate::key(0xff09, true);
874        crate::key(0xff09, false);
875        crate::key(0xff0d, true);
876        host_frame(0., 320, 480, || {
877            ui.begin(viewport());
878            assert_eq!(
879                layout.finish(&mut ui, true, accept).unwrap(),
880                InspectorOutcome::Accepted(ValueChange {
881                    field: 1,
882                    previous: FieldValue::Choice(0),
883                    value: FieldValue::Choice(2)
884                })
885            );
886            assert_eq!(ui.interaction().keyboard_confirmed, Some(14));
887        });
888        host_frame(0., 320, 480, || {
889            ui.begin(viewport());
890            assert_eq!(
891                layout.finish(&mut ui, true, accept).unwrap(),
892                InspectorOutcome::Idle
893            );
894        });
895        crate::key(0xff0d, false);
896        host_frame(0., 320, 480, || {
897            ui.begin(viewport());
898            assert_eq!(
899                layout.finish(&mut ui, true, accept).unwrap(),
900                InspectorOutcome::Idle
901            );
902        });
903    }
904
905    #[test]
906    fn real_remapped_confirm_leaves_gameplay_tap_for_actual_tick_and_blur_cancels() {
907        let mut player = PlayerInput::transient("journey400-285-remap");
908        player
909            .global_action(
910                "confirm",
911                "Confirm",
912                ActionKind::Button,
913                vec![Binding::digital(InputCode::Key(106))],
914            )
915            .unwrap();
916        player
917            .action(
918                "jump",
919                "Jump",
920                ActionKind::Button,
921                vec![Binding::digital(InputCode::Key(32))],
922            )
923            .unwrap();
924        let fields = [field()];
925        let layout = InspectorLayout::new(
926            viewport().bounds(),
927            &fields,
928            UiTheme::preset(ThemeMode::Normal),
929        )
930        .unwrap();
931        let mut ui = Ui::new();
932        host_frame(0., 320, 480, || {
933            player.sample(true);
934            ui.begin(viewport());
935            layout
936                .finish_player(&mut ui, &mut player, true, accept)
937                .unwrap();
938        });
939        crate::key(106, true);
940        crate::key(106, false);
941        crate::key(32, true);
942        crate::key(32, false);
943        host_frame(0., 320, 480, || {
944            player.sample(true);
945            ui.begin(viewport());
946            assert!(matches!(
947                layout
948                    .finish_player(&mut ui, &mut player, true, accept)
949                    .unwrap(),
950                InspectorOutcome::Accepted(_)
951            ));
952            assert_eq!(ui.interaction().player_confirmed, Some(2));
953            // This render frame executes no simulation tick.
954        });
955        host_frame(0., 320, 480, || {
956            player.sample(true);
957            ui.begin(viewport());
958            assert_eq!(
959                layout
960                    .finish_player(&mut ui, &mut player, true, accept)
961                    .unwrap(),
962                InspectorOutcome::Idle
963            );
964            assert!(player.take_tick(["jump"])[0].pressed);
965            assert!(!player.take_tick(["jump"])[0].pressed);
966        });
967        touch(touch::Phase::Start, layout.control_rect(3).unwrap());
968        host_frame(0., 320, 480, || {
969            ui.begin(viewport());
970            layout.finish(&mut ui, true, accept).unwrap();
971        });
972        crate::focus(false);
973        touch(touch::Phase::End, layout.control_rect(3).unwrap());
974        host_frame(0., 320, 480, || {
975            ui.begin(viewport());
976            assert_eq!(
977                layout.finish(&mut ui, true, accept).unwrap(),
978                InspectorOutcome::Idle
979            );
980            assert!(ui.interaction().input_blocked);
981        });
982        crate::focus(true);
983        host_frame(0., 320, 480, || {
984            ui.begin(viewport());
985            assert_eq!(
986                layout.finish(&mut ui, true, accept).unwrap(),
987                InspectorOutcome::Idle
988            );
989        });
990    }
991
992    #[test]
993    fn failed_late_submission_preserves_prior_capture_focus_paint_and_clips() {
994        let fields = [field()];
995        let layout = InspectorLayout::new(
996            viewport().bounds(),
997            &fields,
998            UiTheme::preset(ThemeMode::Normal),
999        )
1000        .unwrap();
1001        let r = layout.control_rect(3).unwrap();
1002        let mut ui = Ui::new();
1003        ui.set_inspection_enabled(true);
1004        touch(touch::Phase::Start, r);
1005        host_frame(0., 320, 480, || {
1006            ui.begin(viewport());
1007            layout.finish(&mut ui, true, accept).unwrap();
1008        });
1009        assert_eq!(ui.interaction().pointer_capture, Some(3));
1010        touch(touch::Phase::End, r);
1011        host_frame(0., 320, 480, || {
1012            ui.begin(viewport());
1013            ui.button(3, r, "PRIOR", true, ButtonStyle::default())
1014                .unwrap();
1015            assert_eq!(
1016                layout.finish(&mut ui, true, accept),
1017                Err(UiError::DuplicateId)
1018            );
1019            assert_eq!(ui.inspect().unwrap().count(), 1);
1020            assert_eq!(ui.focused(), Some(3));
1021            ui.finish(true);
1022            assert!(ui.activated(3));
1023            ui.paint();
1024            let vertices = crate::read(|s| s.vertices.clone());
1025            // Repaint exact restored commands: no leaked panel/labels or clip.
1026            crate::edit(|s| s.vertices.clear());
1027            ui.paint();
1028            assert_eq!(vertices, crate::read(|s| s.vertices.clone()));
1029        });
1030        // A fully clipped inspector cannot own a fresh press.
1031        touch(touch::Phase::Start, r);
1032        touch(touch::Phase::End, r);
1033        host_frame(0., 320, 480, || {
1034            ui.begin(viewport());
1035            ui.push_clip(UiRect {
1036                min: [300., 450.],
1037                size: [10., 10.],
1038            })
1039            .unwrap();
1040            assert_eq!(
1041                layout.finish(&mut ui, true, accept).unwrap(),
1042                InspectorOutcome::Idle
1043            );
1044            assert!(!ui.interaction().pointer_consumed);
1045            ui.pop_clip();
1046        });
1047    }
1048}