ferravex_render/ui/
shared.rs

1//! Bounded screen-space HUD/menu drawing. No camera, lighting or material changes.
2use super::text_layout::{LineLimit, TextBlockMetrics, WrappedLines, WrappedText};
3use super::{AMBER, INK, LINE, PANEL};
4use crate::{
5    Color,
6    input::{InputCode, PlatformEvent, touch},
7};
8pub use ferravex_play::ui::{
9    Anchor, FittedLabel, Rect as UiRect, UiError, Viewport, WidgetId, fit_label, hud_slots, slots,
10};
11use ferravex_play::ui::{UiState, Widget};
12use std::{
13    fmt::{self, Write},
14    ops::Range,
15};
16
17#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
18pub enum Align {
19    #[default]
20    Left,
21    Center,
22    Right,
23}
24#[derive(Clone, Copy, Debug)]
25pub struct TextStyle {
26    pub size: f32,
27    pub color: Color,
28    pub align: Align,
29    /// Wrap at word boundaries, splitting only words wider than the rectangle.
30    pub wrap: bool,
31    pub shadow: bool,
32}
33impl Default for TextStyle {
34    fn default() -> Self {
35        Self {
36            size: 18.,
37            color: INK,
38            align: Align::Left,
39            wrap: false,
40            shadow: false,
41        }
42    }
43}
44#[derive(Clone, Copy, Debug)]
45pub struct ButtonStyle {
46    pub fill: Color,
47    pub ink: Color,
48    pub focus: Color,
49    pub disabled: Color,
50    pub size: f32,
51}
52impl Default for ButtonStyle {
53    fn default() -> Self {
54        Self {
55            fill: PANEL,
56            ink: INK,
57            focus: AMBER,
58            disabled: LINE,
59            size: 18.,
60        }
61    }
62}
63#[derive(Clone)]
64enum Kind {
65    Panel(Color),
66    Gradient(Color, Color),
67    Text(Range<usize>, TextStyle, LineLimit),
68    Button(WidgetId, Range<usize>, ButtonStyle, bool),
69}
70#[derive(Clone)]
71struct Command {
72    rect: UiRect,
73    clip: UiRect,
74    kind: Kind,
75}
76/// Read-only ownership summary for the most recently finished host frame.
77///
78/// Sample `PlayerInput`, submit UI, call [`Ui::finish_player`], then inspect
79/// [`Ui::interaction`] **before** translating fresh pointer edges into scene
80/// commands. Reject scene pointer commands when `pointer_consumed` or
81/// `input_blocked` is true. Keep accepted commands in a bounded caller queue
82/// until an actual simulation tick; a later frame's summary cannot classify an
83/// earlier, buffered gameplay edge. Do not bind that same scene pointer action
84/// independently through `PlayerInput` and then gate it using a later summary.
85/// Unrelated movement/jump actions still use `PlayerInput::take_tick` in ticks.
86/// Local UI must not stop authoritative network/replay ticks.
87///
88/// This is a conservative frame aggregate, not an event list: several pointer
89/// gestures in one frame share one consumed flag; activation fields retain the
90/// last accepted ID **per source**, while [`Ui::activated`] retains the last ID
91/// overall. It never drains the platform journal or gameplay actions. The
92/// existing `finish_player` consumption of the global `confirm` is unchanged.
93///
94/// Enabled and disabled buttons own presses in their visible clipped bounds.
95/// A disabled top button blocks lower buttons and the world, without activating.
96/// Fully clipped buttons do not own presses. Panels/text are paint only, even
97/// if visually opaque; use [`Ui::modal`] for an explicit viewport-wide blocker.
98/// A modal discards lower interaction widgets, but preserves their paint order.
99/// Ownership is assigned on press, so a world press dragged onto UI stays world.
100/// Only the UI's existing primary-mouse/one-touch route is classified; secondary
101/// mouse buttons and additional touches need caller policy.
102///
103/// ```
104/// use ferravex_render::ui::UiInteraction;
105/// let idle = UiInteraction::default();
106/// assert!(!idle.pointer_consumed && !idle.input_blocked);
107/// assert_eq!(idle.pointer_capture, None);
108/// ```
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
110pub struct UiInteraction {
111    /// Some part of a UI-owned primary gesture occurred or remained held this
112    /// frame, including release outside, cancellation and a removed/disabled ID.
113    pub pointer_consumed: bool,
114    /// Original widget owning the still-held gesture, including its cancelled
115    /// tail. This can name a removed widget; it does not promise activation.
116    pub pointer_capture: Option<WidgetId>,
117    /// Last accepted pointer release, including a nonfocusable modal blocker.
118    pub pointer_activated: Option<WidgetId>,
119    /// Last focused widget accepted by the built-in keyboard Enter route.
120    pub keyboard_confirmed: Option<WidgetId>,
121    /// Last focused widget accepted by the selected gamepad's A route.
122    pub gamepad_confirmed: Option<WidgetId>,
123    /// Last focused widget accepted by the player's remapped global `confirm`.
124    /// Its physical device is not inferred; it may also match a built-in route.
125    pub player_confirmed: Option<WidgetId>,
126    /// Focus loss, journal overflow or the host Controls editor blocks input.
127    /// Cancel caller-owned scene gestures too; simulation may keep progressing.
128    /// `finish(false)` only disables UI, so it does not itself set this flag.
129    /// Once observed, this stays true for the rest of that host frame.
130    pub input_blocked: bool,
131}
132
133/// Semantic kind of an accepted UI submission. Paint-only items have no ID.
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum UiRole {
137    Panel,
138    Gradient,
139    Text,
140    Button,
141    /// The latest explicit, nonfocusable viewport-wide modal input blocker.
142    ModalBlocker,
143}
144
145/// Complete original UTF-8 copy, or an explicit inspection-only capacity miss.
146/// Missing copy never rejects painting/input and is never silently truncated.
147#[derive(Clone, Copy, Debug, PartialEq, Eq)]
148pub enum UiLabel<'a> {
149    Full(&'a str),
150    Unavailable { required_bytes: usize },
151}
152
153/// Borrowed description of one accepted submission, in composition order.
154/// Read after finishing layout/input for current focus. Bounds are the exact
155/// logical rectangles used by painting/hit testing, before viewport projection.
156/// `visible_bounds` is their positive-area clip intersection, **not** ink bounds,
157/// occlusion, or a promise that truncated/limited text is all painted. Panels,
158/// text and gradients are paint only. Earlier modal scopes remain inspectable.
159#[derive(Clone, Copy, Debug, PartialEq)]
160pub struct UiElement<'a> {
161    pub id: Option<WidgetId>,
162    pub role: UiRole,
163    pub label: UiLabel<'a>,
164    /// Actual retained painter copy (possibly ellipsized); empty for decoration.
165    pub painted_label: &'a str,
166    pub bounds: UiRect,
167    pub visible_bounds: Option<UiRect>,
168    /// Submitted button state, not the host/global input enable flag.
169    pub enabled: bool,
170    pub focused: bool,
171    /// Button belongs to the latest modal scope, or is its blocker. Disabled
172    /// buttons are still registered and can own/block pointer gestures.
173    pub interaction_registered: bool,
174}
175
176struct InspectionLabel {
177    command: usize,
178    range: Option<Range<usize>>,
179    required_bytes: usize,
180}
181struct InspectionStorage {
182    labels: Vec<InspectionLabel>,
183    text: String,
184    active: bool,
185}
186impl InspectionStorage {
187    fn new() -> Self {
188        Self {
189            labels: Vec::with_capacity(1024),
190            text: String::with_capacity(32768),
191            active: false,
192        }
193    }
194}
195
196/// Allocation-free borrowed traversal; obtained only by opting in before
197/// [`Ui::begin`]. At most 1024 commands plus the latest modal blocker. IDs may
198/// repeat across discarded modal scopes; use order and `interaction_registered`.
199/// All borrows expire before another mutable UI operation, including `begin`.
200#[derive(Clone)]
201pub struct UiInspection<'a> {
202    ui: &'a Ui,
203    storage: &'a InspectionStorage,
204    command: usize,
205    label: usize,
206    blocker_pending: bool,
207}
208impl<'a> Iterator for UiInspection<'a> {
209    type Item = UiElement<'a>;
210    fn next(&mut self) -> Option<Self::Item> {
211        if self.blocker_pending && self.command == self.ui.modal_start {
212            self.blocker_pending = false;
213            let bounds = self.ui.viewport.bounds();
214            return Some(UiElement {
215                id: self.ui.modal_blocker,
216                role: UiRole::ModalBlocker,
217                label: UiLabel::Full(""),
218                painted_label: "",
219                bounds,
220                visible_bounds: bounds.intersect(bounds),
221                enabled: true,
222                focused: false,
223                interaction_registered: true,
224            });
225        }
226        let index = self.command;
227        let command = self.ui.commands.get(index)?;
228        self.command += 1;
229        let (id, role, painted_label, enabled) = match &command.kind {
230            Kind::Panel(_) => (None, UiRole::Panel, "", false),
231            Kind::Gradient(..) => (None, UiRole::Gradient, "", false),
232            Kind::Text(range, ..) => (None, UiRole::Text, &self.ui.text[range.clone()], false),
233            Kind::Button(id, range, _, enabled) => (
234                Some(*id),
235                UiRole::Button,
236                &self.ui.text[range.clone()],
237                *enabled,
238            ),
239        };
240        let mut label = UiLabel::Full(painted_label);
241        if let Some(full) = self
242            .storage
243            .labels
244            .get(self.label)
245            .filter(|l| l.command == index)
246        {
247            self.label += 1;
248            label = match &full.range {
249                Some(range) => UiLabel::Full(&self.storage.text[range.clone()]),
250                None => UiLabel::Unavailable {
251                    required_bytes: full.required_bytes,
252                },
253            };
254        }
255        let visible_bounds = command.rect.intersect(command.clip);
256        let interaction_registered = id.is_some() && index >= self.ui.modal_start;
257        Some(UiElement {
258            id,
259            role,
260            label,
261            painted_label,
262            bounds: command.rect,
263            visible_bounds,
264            enabled,
265            focused: interaction_registered
266                && enabled
267                && visible_bounds.is_some()
268                && id == self.ui.state.focused(),
269            interaction_registered,
270        })
271    }
272    fn size_hint(&self) -> (usize, Option<usize>) {
273        let len = self.ui.commands.len() - self.command + usize::from(self.blocker_pending);
274        (len, Some(len))
275    }
276}
277impl ExactSizeIterator for UiInspection<'_> {}
278impl std::iter::FusedIterator for UiInspection<'_> {}
279
280/// Diagnostic export failure; UI, input and the caller buffer are unchanged.
281#[derive(Clone, Copy, Debug, PartialEq, Eq)]
282pub enum UiInspectionExportError {
283    Disabled,
284    Capacity { required_bytes: usize },
285}
286
287#[derive(Clone, Copy)]
288enum OwnedPointer {
289    Mouse,
290    Touch(u64),
291}
292
293struct CompositionCheckpoint {
294    commands: usize,
295    text: usize,
296    vertices: usize,
297    clips: [UiRect; 16],
298    clip_len: usize,
299    modal_start: usize,
300    modal_blocker: Option<WidgetId>,
301    inspection: Option<(usize, usize)>,
302}
303
304/// Restricted drawing/widget submission inside [`Ui::compose`].
305///
306/// Methods use the existing command budgets and styles. The first submission
307/// error is sticky: later submissions return it without modifying the UI, and
308/// the group fails even if the callback ignores that error. No mutable `Ui`,
309/// input delivery, focus changes, painting, lifecycle or configuration is exposed.
310/// Callback/formatting side effects outside the UI cannot be rolled back.
311///
312/// Clips must be balanced within each group; popping an inherited clip or
313/// leaving a new clip open rejects the group with [`UiError::InvalidLayout`].
314/// Nested groups have independent rollback and may be replaced by a fallback;
315/// propagate their error with `?` to reject the containing group. At most 16
316/// groups may be active, including the outermost group. Checkpoints use fixed
317/// stack storage; no command/text arena is cloned or widget undo journal kept.
318///
319/// See [`Ui::compose`] for a complete result-card/fallback recipe.
320/// Input and lifecycle operations are intentionally unavailable:
321///
322/// ```compile_fail
323/// use ferravex_render::ui::{Ui, Viewport};
324/// let mut ui = Ui::new();
325/// ui.begin(Viewport::responsive([320., 240.], [0.; 4]).unwrap());
326/// ui.compose(|group| {
327///     group.finish(true); // Input delivery cannot be rolled back.
328///     Ok(())
329/// }).unwrap();
330/// ```
331pub struct UiComposition<'a> {
332    ui: &'a mut Ui,
333    checkpoint: Option<CompositionCheckpoint>,
334    error: Option<UiError>,
335    depth: usize,
336}
337impl UiComposition<'_> {
338    fn run<R>(
339        ui: &mut Ui,
340        depth: usize,
341        build: impl FnOnce(&mut UiComposition<'_>) -> Result<R, UiError>,
342    ) -> Result<R, UiError> {
343        if depth > 16 {
344            return Err(UiError::Capacity);
345        }
346        let checkpoint = CompositionCheckpoint {
347            commands: ui.commands.len(),
348            text: ui.text.len(),
349            vertices: ui.vertices,
350            clips: ui.clips,
351            clip_len: ui.clip_len,
352            modal_start: ui.modal_start,
353            modal_blocker: ui.modal_blocker,
354            inspection: ui
355                .inspection
356                .as_ref()
357                .map(|s| (s.labels.len(), s.text.len())),
358        };
359        let mut group = UiComposition {
360            ui,
361            checkpoint: Some(checkpoint),
362            error: None,
363            depth,
364        };
365        let result = build(&mut group);
366        if let Some(error) = group.error {
367            return Err(error);
368        }
369        let value = result?;
370        if group.ui.clip_len != group.checkpoint.as_ref().unwrap().clip_len {
371            return Err(UiError::InvalidLayout);
372        }
373        group.checkpoint = None;
374        Ok(value)
375    }
376    fn submit<R>(
377        &mut self,
378        submit: impl FnOnce(&mut Ui) -> Result<R, UiError>,
379    ) -> Result<R, UiError> {
380        if let Some(error) = self.error {
381            return Err(error);
382        }
383        let result = submit(self.ui);
384        if let Err(error) = result {
385            self.error = Some(error);
386        }
387        result
388    }
389    /// Independently atomic subgroup. A handled error does not poison this
390    /// group; use `?` to propagate it. Depth 17 rejects before calling `build`.
391    pub fn compose<R>(
392        &mut self,
393        build: impl FnOnce(&mut UiComposition<'_>) -> Result<R, UiError>,
394    ) -> Result<R, UiError> {
395        if let Some(error) = self.error {
396            return Err(error);
397        }
398        UiComposition::run(self.ui, self.depth + 1, build)
399    }
400    /// Same logical geometry and validation as [`Ui::push_clip`].
401    pub fn push_clip(&mut self, rect: UiRect) -> Result<(), UiError> {
402        self.submit(|ui| ui.push_clip(rect))
403    }
404    /// Pop only a clip pushed in this group; inherited clips remain protected.
405    pub fn pop_clip(&mut self) -> Result<(), UiError> {
406        let floor = self.checkpoint.as_ref().unwrap().clip_len;
407        self.submit(|ui| {
408            if ui.clip_len == floor {
409                return Err(UiError::InvalidLayout);
410            }
411            ui.pop_clip();
412            Ok(())
413        })
414    }
415    /// Same modal scope change as [`Ui::modal`], restored if this group fails.
416    /// Repeated modal calls reuse widget storage; no destructive-operation log.
417    pub fn modal(&mut self, blocker: WidgetId) -> Result<(), UiError> {
418        self.submit(|ui| ui.modal(blocker))
419    }
420    /// Submit using [`Ui::panel`].
421    pub fn panel(&mut self, rect: UiRect, color: Color) -> Result<(), UiError> {
422        self.submit(|ui| ui.panel(rect, color))
423    }
424    /// Submit using [`Ui::gradient`].
425    pub fn gradient(&mut self, rect: UiRect, left: Color, right: Color) -> Result<(), UiError> {
426        self.submit(|ui| ui.gradient(rect, left, right))
427    }
428    /// Submit using [`Ui::text_fmt`]; formatting runs only until the first error.
429    pub fn text_fmt(
430        &mut self,
431        rect: UiRect,
432        style: TextStyle,
433        args: fmt::Arguments<'_>,
434    ) -> Result<(), UiError> {
435        self.submit(|ui| ui.text_fmt(rect, style, args))
436    }
437    /// Submit using [`Ui::text`].
438    pub fn text(&mut self, rect: UiRect, text: &str, style: TextStyle) -> Result<(), UiError> {
439        self.submit(|ui| ui.text(rect, text, style))
440    }
441    /// Submit using [`Ui::wrapped_text`], returning its measured block metrics.
442    pub fn wrapped_text(
443        &mut self,
444        rect: UiRect,
445        text: &str,
446        style: TextStyle,
447        limit: LineLimit,
448    ) -> Result<TextBlockMetrics, UiError> {
449        self.submit(|ui| ui.wrapped_text(rect, text, style, limit))
450    }
451    /// Submit using [`Ui::label`], including full inspection copy when opted in.
452    pub fn label(&mut self, rect: UiRect, text: &str, style: TextStyle) -> Result<(), UiError> {
453        self.submit(|ui| ui.label(rect, text, style))
454    }
455    /// Submit using [`Ui::button`].
456    pub fn button(
457        &mut self,
458        id: WidgetId,
459        rect: UiRect,
460        text: &str,
461        enabled: bool,
462        style: ButtonStyle,
463    ) -> Result<(), UiError> {
464        self.submit(|ui| ui.button(id, rect, text, enabled, style))
465    }
466    /// Submit using [`Ui::hud_button`].
467    pub fn hud_button(
468        &mut self,
469        id: WidgetId,
470        rect: UiRect,
471        text: &str,
472        enabled: bool,
473        style: ButtonStyle,
474    ) -> Result<(), UiError> {
475        self.submit(|ui| ui.hud_button(id, rect, text, enabled, style))
476    }
477    /// Submit using [`Ui::button_with_options`].
478    pub fn button_with_options(
479        &mut self,
480        id: WidgetId,
481        rect: UiRect,
482        text: &str,
483        options: super::ButtonOptions,
484        style: ButtonStyle,
485    ) -> Result<(), UiError> {
486        self.submit(|ui| ui.button_with_options(id, rect, text, options, style))
487    }
488    /// Submit using [`Ui::hud_button_with_options`].
489    pub fn hud_button_with_options(
490        &mut self,
491        id: WidgetId,
492        rect: UiRect,
493        text: &str,
494        options: super::ButtonOptions,
495        style: ButtonStyle,
496    ) -> Result<(), UiError> {
497        self.submit(|ui| ui.hud_button_with_options(id, rect, text, options, style))
498    }
499}
500impl Drop for UiComposition<'_> {
501    fn drop(&mut self) {
502        let Some(saved) = self.checkpoint.take() else {
503            return;
504        };
505        self.ui.commands.truncate(saved.commands);
506        self.ui.text.truncate(saved.text);
507        self.ui.vertices = saved.vertices;
508        self.ui.clips = saved.clips;
509        self.ui.clip_len = saved.clip_len;
510        self.ui.modal_start = saved.modal_start;
511        self.ui.modal_blocker = saved.modal_blocker;
512        if let (Some(storage), Some((labels, text))) = (&mut self.ui.inspection, saved.inspection) {
513            storage.labels.truncate(labels);
514            storage.text.truncate(text);
515        }
516        // Only add/begin_frame are exposed through composition. Neither mutates
517        // focus/capture, so reconstruct registrations from the retained painter
518        // commands without calling end_frame or maintaining a widget journal.
519        // These exact widgets already fitted before the group started.
520        self.ui.state.begin_frame();
521        if let Some(id) = saved.modal_blocker {
522            self.ui
523                .state
524                .add(Widget {
525                    id,
526                    rect: self.ui.viewport.bounds(),
527                    clip: Some(self.ui.viewport.bounds()),
528                    enabled: true,
529                    focusable: false,
530                })
531                .expect("retained modal registration fits");
532        }
533        for command in &self.ui.commands[saved.modal_start..] {
534            if let Kind::Button(id, _, _, enabled) = command.kind {
535                self.ui
536                    .state
537                    .add(Widget {
538                        id,
539                        rect: command.rect,
540                        clip: Some(command.clip),
541                        enabled,
542                        focusable: true,
543                    })
544                    .expect("retained widget registration fits");
545            }
546        }
547    }
548}
549
550/// Reuse one instance across frames. Errors reject a command atomically.
551/// Budgets: 1024 commands/widgets, 32 KiB UTF-8, 196608 vertices and 16 clip levels.
552pub struct Ui {
553    state: UiState,
554    commands: Vec<Command>,
555    text: String,
556    clips: [UiRect; 16],
557    clip_len: usize,
558    viewport: Viewport,
559    vertices: usize,
560    active: Option<WidgetId>,
561    hovered: Option<WidgetId>,
562    touch: Option<u64>,
563    frame: Option<u64>,
564    epoch: u64,
565    shift: u8,
566    pad_epoch: Option<(u8, u32)>,
567    auto_focus: bool,
568    mouse_capture: bool,
569    interaction: UiInteraction,
570    owned_pointer: Option<(OwnedPointer, WidgetId)>,
571    modal_start: usize,
572    modal_blocker: Option<WidgetId>,
573    inspection: Option<Box<InspectionStorage>>,
574}
575impl Default for Ui {
576    fn default() -> Self {
577        Self::new()
578    }
579}
580impl Ui {
581    /// Submit an atomic group through a restricted [`UiComposition`].
582    ///
583    /// On an ordinary submission/callback error, restore commands, text, vertex
584    /// estimates, clips, inspection copy/metadata and modal/widget registrations.
585    /// Prior focus, capture and [`UiInteraction`] are preserved: input is not
586    /// delivered within the group. Success commits all submissions and returns
587    /// the callback's value. The first submission error wins over a later error.
588    /// Nested errors may be handled locally; see [`UiComposition::compose`].
589    ///
590    /// Rollback truncates append-only arenas and reconstructs at most 1024
591    /// widgets from retained commands. Existing duplicate-ID checking makes
592    /// reconstruction at worst quadratic in that fixed widget bound. No heap
593    /// scratch, arena clones or unbounded undo log are needed, including for
594    /// repeated modal replacements. Each active group saves a 16-entry clip
595    /// array and scalar checkpoints, with a maximum nesting depth of 16.
596    ///
597    /// The drop guard also restores UI during Rust panic unwinding; it does not
598    /// catch panics, handle abort/allocation failure or undo callback/formatter
599    /// side effects outside this UI. Do not paint, deliver input or perform game
600    /// actions indirectly from a callback. Compose before finishing/painting.
601    ///
602    /// This headless result-card recipe exercises both success and a rejected
603    /// oversized body. A small explicit fallback retains the same readable
604    /// primary action. Start with room for that fallback; if prior groups use
605    /// all budgets, even a fallback can reject and its error must be handled.
606    /// Game rules/feedback run later from accepted actions, on actual ticks.
607    ///
608    /// ```
609    /// use ferravex_render::ui::{ButtonStyle, TextStyle, Ui, UiError, UiRect,
610    ///     UiLabel, Viewport, PANEL, text_layout::LineLimit};
611    /// let mut ui = Ui::new(); // Reuse across frames.
612    /// ui.set_inspection_enabled(true); // Optional host diagnostics.
613    /// let viewport = Viewport::responsive([320., 240.], [0.; 4])?;
614    /// let card = UiRect { min: [12.; 2], size: [296., 216.] };
615    /// let title = UiRect { min: [24., 24.], size: [272., 28.] };
616    /// let body = UiRect { min: [24., 64.], size: [272., 90.] };
617    /// let action = UiRect { min: [24., 172.], size: [272., 44.] };
618    /// let oversized = "x".repeat(32769); // Inject a rejected result payload.
619    /// for (copy, rejected) in [("DELIVERY COMPLETE", false), (&oversized, true)] {
620    ///     ui.begin(viewport);
621    ///     let result = ui.compose(|card_ui| {
622    ///         card_ui.modal(900)?;
623    ///         card_ui.panel(card, PANEL)?;
624    ///         card_ui.label(title, "RESULTS", TextStyle::default())?;
625    ///         card_ui.wrapped_text(body, copy, TextStyle::default(), LineLimit::Clip(5))?;
626    ///         card_ui.hud_button(901, action, "CONTINUE", true, ButtonStyle::default())
627    ///     });
628    ///     assert_eq!(result.is_err(), rejected);
629    ///     if result.is_err() {
630    ///         ui.compose(|fallback| {
631    ///             fallback.modal(900)?;
632    ///             fallback.panel(card, PANEL)?;
633    ///             fallback.label(title, "RESULTS UNAVAILABLE", TextStyle::default())?;
634    ///             fallback.hud_button(901, action, "CONTINUE", true, ButtonStyle::default())
635    ///         })?;
636    ///     }
637    ///     ui.finish(true); // Deliver input only after choosing the full group.
638    ///     let primary = ui.inspect().unwrap().find(|e| e.id == Some(901)).unwrap();
639    ///     assert_eq!(primary.label, UiLabel::Full("CONTINUE"));
640    ///     assert!(primary.enabled && primary.interaction_registered);
641    ///     assert_eq!(primary.visible_bounds, Some(action));
642    ///     ui.paint();
643    /// }
644    /// # Ok::<(), UiError>(())
645    /// ```
646    pub fn compose<R>(
647        &mut self,
648        build: impl FnOnce(&mut UiComposition<'_>) -> Result<R, UiError>,
649    ) -> Result<R, UiError> {
650        UiComposition::run(self, 1, build)
651    }
652    pub fn new() -> Self {
653        let viewport = Viewport::fit([1.; 2], [1.; 2], [0.; 4]).unwrap();
654        Self {
655            state: UiState::with_capacity(1024),
656            commands: Vec::with_capacity(1024),
657            text: String::with_capacity(32768),
658            clips: [viewport.bounds(); 16],
659            clip_len: 1,
660            viewport,
661            vertices: 0,
662            active: None,
663            hovered: None,
664            touch: None,
665            frame: None,
666            epoch: 0,
667            shift: 0,
668            pad_epoch: None,
669            auto_focus: true,
670            mouse_capture: false,
671            interaction: UiInteraction::default(),
672            owned_pointer: None,
673            modal_start: 0,
674            modal_blocker: None,
675            inspection: None,
676        }
677    }
678    /// Reserved CPU storage, including this value; excludes the renderer's shared stream.
679    pub fn reserved_bytes(&self) -> usize {
680        std::mem::size_of::<Self>()
681            + self.commands.capacity() * std::mem::size_of::<Command>()
682            + self.text.capacity()
683            + self.state.capacity() * std::mem::size_of::<Widget>()
684            + self.inspection.as_ref().map_or(0, |s| {
685                std::mem::size_of::<InspectionStorage>()
686                    + s.labels.capacity() * std::mem::size_of::<InspectionLabel>()
687                    + s.text.capacity()
688            })
689    }
690    /// Opt in before `begin`; enabling allocates bounded supplemental storage
691    /// once. Inspection starts at the next `begin`, so shortened labels from an
692    /// earlier submission are never misreported as full. Disabling immediately
693    /// drops this storage. Default-off instances retain the original arenas and
694    /// submission behavior, with only one added optional pointer in `Ui`.
695    ///
696    /// Ordinary text/button copy borrows the existing paint arena. Only shortened
697    /// `label`/`hud_button` source uses an extra 32 KiB UTF-8 arena and at most
698    /// 1024 metadata entries. Overflow yields `UiLabel::Unavailable`, without
699    /// changing command acceptance. `begin` clears all inspection copy and IDs.
700    pub fn set_inspection_enabled(&mut self, enabled: bool) {
701        if enabled && self.inspection.is_none() {
702            self.inspection = Some(Box::new(InspectionStorage::new()));
703        } else if !enabled {
704            self.inspection = None;
705        }
706    }
707    /// Inspect accepted submissions without consuming input or modifying paint.
708    /// Rejected commands never appear. The latest modal blocker is synthesized
709    /// from existing modal state; earlier buttons remain with registration false.
710    /// No snapshot history or action-execution API is provided.
711    ///
712    /// Runnable native/headless host recipe: compose actual UI, locate a visible
713    /// action by its full label, project its clipped geometry for host diagnostics,
714    /// then explicitly export into a bounded caller buffer. Hosts choose where
715    /// (or whether) to publish these diagnostics; there is no global/Wasm export.
716    ///
717    /// ```
718    /// use ferravex_render::{input::host_frame, ui::{ButtonStyle, Ui,
719    ///     UiLabel, UiRect, UiRole, Viewport}};
720    /// let viewport = Viewport::fit([400., 200.], [100.; 2], [0.; 4]).unwrap();
721    /// let mut ui = Ui::new();
722    /// ui.set_inspection_enabled(true); // Setup, outside the frame loop.
723    /// host_frame(0., 400, 200, || {
724    ///     ui.begin(viewport);
725    ///     ui.push_clip(UiRect { min: [20., 30.], size: [10., 20.] }).unwrap();
726    ///     ui.hud_button(7, UiRect { min: [10., 20.], size: [80., 40.] },
727    ///         "RESUME EXPEDITION", true, ButtonStyle::default()).unwrap();
728    ///     ui.finish(true);
729    ///     let action = ui.inspect().unwrap().find(|e| e.role == UiRole::Button
730    ///         && e.label == UiLabel::Full("RESUME EXPEDITION")).unwrap();
731    ///     assert_eq!(action.id, Some(7));
732    ///     let visible = action.visible_bounds.unwrap();
733    ///     assert_eq!(visible, UiRect { min: [20., 30.], size: [10., 20.] });
734    ///     assert!(visible.contains([25., 40.])); // Same half-open hit geometry.
735    ///     let pixel = std::array::from_fn::<_, 2, _>(|i|
736    ///         viewport.pixels().min[i] + [25., 40.][i] * viewport.scale());
737    ///     assert_eq!(pixel, [150., 80.]);
738    ///     ui.paint(); // Inspection leaves the normal paint path intact.
739    ///     let mut diagnostic = [0_u8; 2048];
740    ///     let written = ui.write_inspection(&mut diagnostic).unwrap();
741    ///     let json = std::str::from_utf8(&diagnostic[..written]).unwrap();
742    ///     assert!(json.contains("RESUME EXPEDITION"));
743    ///     assert!(json.contains("\"visible_bounds\":[20,30,10,20]"));
744    /// });
745    /// ```
746    pub fn inspect(&self) -> Option<UiInspection<'_>> {
747        let storage = self.inspection.as_deref().filter(|s| s.active)?;
748        Some(UiInspection {
749            ui: self,
750            storage,
751            command: 0,
752            label: 0,
753            blocker_pending: self.modal_blocker.is_some(),
754        })
755    }
756    /// Write diagnostic JSON schema 1 (UTF-8, no terminator) to caller storage.
757    /// Its `elements` follow `inspect`; IDs are decimal strings (lossless u64
758    /// in JavaScript), rectangles are `[x,y,width,height]` in
759    /// logical units. Unavailable labels are null with `label_required_bytes`.
760    /// This is a diagnostic format, not scene/save/replay or an action protocol.
761    /// Two bounded passes determine required bytes before writing: insufficient
762    /// output returns its exact requirement and leaves the entire buffer intact.
763    /// The tail after the returned byte count is unchanged. Disabled inspection
764    /// returns `Disabled`, rather than misleadingly exporting an empty scene.
765    pub fn write_inspection(&self, output: &mut [u8]) -> Result<usize, UiInspectionExportError> {
766        let inspection = self.inspect().ok_or(UiInspectionExportError::Disabled)?;
767        let mut count = InspectionCount(0);
768        write_inspection_json(inspection.clone(), &mut count).expect("counting cannot fail");
769        if output.len() < count.0 {
770            return Err(UiInspectionExportError::Capacity {
771                required_bytes: count.0,
772            });
773        }
774        write_inspection_json(
775            inspection,
776            &mut InspectionOutput {
777                bytes: output,
778                len: 0,
779            },
780        )
781        .expect("preflighted output capacity");
782        Ok(count.0)
783    }
784    // Only called after a successful command. Command budget bounds metadata;
785    // no inspection capacity failure can alter paint or interaction acceptance.
786    fn inspect_full_label(&mut self, source: &str, shortened: bool) {
787        if !shortened {
788            return;
789        }
790        if let Some(storage) = self.inspection.as_deref_mut().filter(|s| s.active) {
791            let range = if source.len() <= 32768 - storage.text.len() {
792                let start = storage.text.len();
793                storage.text.push_str(source);
794                Some(start..storage.text.len())
795            } else {
796                None
797            };
798            storage.labels.push(InspectionLabel {
799                command: self.commands.len() - 1,
800                range,
801                required_bytes: source.len(),
802            });
803        }
804    }
805    pub fn begin(&mut self, viewport: Viewport) {
806        if let Some(storage) = &mut self.inspection {
807            storage.labels.clear();
808            storage.text.clear();
809            storage.active = true;
810        }
811        self.viewport = viewport;
812        self.commands.clear();
813        self.text.clear();
814        self.vertices = 0;
815        self.clips[0] = viewport.bounds();
816        self.clip_len = 1;
817        self.state.begin_frame();
818        self.active = None;
819        self.modal_start = 0;
820        self.modal_blocker = None;
821    }
822    /// Discard lower widgets from interaction while preserving their paint order.
823    /// Queue a full-screen panel after this call and before modal buttons.
824    pub fn modal(&mut self, blocker: WidgetId) -> Result<(), UiError> {
825        self.state.begin_frame();
826        self.state.add(Widget {
827            id: blocker,
828            rect: self.viewport.bounds(),
829            clip: Some(self.viewport.bounds()),
830            enabled: true,
831            focusable: false,
832        })?;
833        self.modal_start = self.commands.len();
834        self.modal_blocker = Some(blocker);
835        Ok(())
836    }
837    /// Menus may accept the first button immediately; gameplay overlays can require
838    /// explicit navigation/pointer focus so a shared gamepad action keeps its role.
839    pub fn set_auto_focus(&mut self, enabled: bool) {
840        self.auto_focus = enabled;
841    }
842    pub fn focused(&self) -> Option<WidgetId> {
843        self.state.focused()
844    }
845    /// Enabled widget under the pointer as of the last finished frame (the
846    /// same hover that [`Self::paint`] highlights). Used by `ui::kit` visuals.
847    pub fn hovered(&self) -> Option<WidgetId> {
848        self.hovered
849    }
850    /// Viewport passed to the most recent [`Self::begin`].
851    pub fn viewport(&self) -> Viewport {
852        self.viewport
853    }
854    pub fn activated(&self, id: WidgetId) -> bool {
855        self.active == Some(id)
856    }
857    /// Inspect after finishing UI, before translating this frame's scene input.
858    /// Repeated reads/finishes in one host frame retain the aggregate, including
859    /// across `begin`; the next host frame's finish resets transient fields.
860    /// No allocations or input consumption occur here. See [`UiInteraction`]
861    /// for routing policy and the runnable tick-queue recipe below.
862    ///
863    /// This headless recipe uses injected primary touches in logical pixels.
864    /// Its one-slot queue rejects new requests while full (no overwrite). A real
865    /// host passes its fresh pointer press/position at the same point; mouse
866    /// polling can use `is_mouse_button_pressed(MouseButton::Left)`. Do not read
867    /// a tick-buffered fire action here. Buy/drop are requests: rules and feedback
868    /// run only when the actual tick accepts them. Reset the queue on restart.
869    ///
870    /// ```
871    /// use ferravex_core::session::GameSession;
872    /// use ferravex_render::{Vec2, input::{ActionKind, Binding, InputCode,
873    ///     PlayerInput, host_frame, touch, touch_event},
874    ///     ui::{ButtonStyle, Ui, UiRect, Viewport}};
875    /// #[derive(Clone, Copy, Debug, PartialEq)]
876    /// enum Command { Buy, Drop([f32; 2]) }
877    /// let mut ui = Ui::new();
878    /// let mut player = PlayerInput::transient("ui-world-recipe");
879    /// player.action("jump", "Jump", ActionKind::Button,
880    ///     vec![Binding::digital(InputCode::Key(32))]).unwrap();
881    /// let viewport = Viewport::responsive([320., 240.], [0.; 4]).unwrap();
882    /// let mut session = GameSession::try_new(64., 4, true).unwrap();
883    /// let mut pending = None; // Bounded one-slot command queue.
884    /// let mut executed = Vec::new(); // Test observation, not the command queue.
885    /// for (id, position, elapsed) in [
886    ///     (1, [30., 30.], 0.), // Buy: zero ticks; no scene drop.
887    ///     (2, [180., 160.], 0.), // Queue full: this request is rejected.
888    ///     (3, [180., 160.], 1. / 64.), // First actual tick executes Buy.
889    ///     (4, [180., 160.], 1. / 64.), // World drop executes once.
890    /// ] {
891    ///     for phase in [touch::Phase::Start, touch::Phase::End] {
892    ///         touch_event(touch::Event { id, phase,
893    ///             position: Vec2::from(position) });
894    ///     }
895    ///     host_frame(elapsed as f32, 320, 240, || {
896    ///         player.sample(true); // Sample globals/gameplay without ticking.
897    ///         ui.begin(viewport);
898    ///         ui.button(10, UiRect { min: [20.; 2], size: [100., 44.] },
899    ///             "BUY", true, ButtonStyle::default()).unwrap();
900    ///         ui.finish_player(&mut player, true);
901    ///         let ownership = ui.interaction();
902    ///         let request = if ui.activated(10) { Some(Command::Buy) }
903    ///             else if !ownership.input_blocked && !ownership.pointer_consumed {
904    ///                 Some(Command::Drop(position)) // This host's fresh press.
905    ///             } else { None };
906    ///         if pending.is_none() { pending = request; } // Explicit full policy.
907    ///         let frame = session.advance(elapsed);
908    ///         for _ in frame.ticks() { // Only actually executed updates consume.
909    ///             let [_jump] = player.take_tick(["jump"]);
910    ///             if let Some(command) = pending.take() { executed.push(command); }
911    ///         }
912    ///         ui.paint();
913    ///     });
914    /// }
915    /// assert_eq!(executed, [Command::Buy, Command::Drop([180., 160.])]);
916    /// assert_eq!(pending, None);
917    /// ```
918    pub fn interaction(&self) -> UiInteraction {
919        self.interaction
920    }
921    /// Cancel activation but retain an owned gesture's tail until release, so
922    /// closing/removing UI cannot turn that release into a scene action. Focus
923    /// loss/overflow reset ownership because the journal can no longer prove it.
924    pub fn cancel(&mut self) {
925        self.state.cancel_pointer();
926        self.touch = None;
927        self.mouse_capture = false;
928    }
929    fn ownership_hit(&self, point: [f32; 2]) -> Option<WidgetId> {
930        self.commands[self.modal_start..]
931            .iter()
932            .rev()
933            .find_map(|command| match command.kind {
934                Kind::Button(id, ..)
935                    if command.rect.contains(point) && command.clip.contains(point) =>
936                {
937                    Some(id)
938                }
939                _ => None,
940            })
941            .or(self
942                .modal_blocker
943                .filter(|_| self.viewport.bounds().contains(point)))
944    }
945    fn own_pointer(&mut self, pointer: OwnedPointer, point: [f32; 2]) {
946        if self.owned_pointer.is_none() {
947            self.owned_pointer = self.ownership_hit(point).map(|id| (pointer, id));
948        }
949        if self.owned_pointer.is_some() {
950            self.interaction.pointer_consumed = true;
951        }
952    }
953    fn pointer_up(&mut self, point: [f32; 2]) {
954        let accepted = self.state.pointer_up(point);
955        self.active = accepted.or(self.active);
956        self.interaction.pointer_consumed |= accepted.is_some();
957        self.interaction.pointer_activated = accepted.or(self.interaction.pointer_activated);
958    }
959    pub fn push_clip(&mut self, rect: UiRect) -> Result<(), UiError> {
960        if !rect.valid() {
961            return Err(UiError::InvalidLayout);
962        }
963        if self.clip_len == 16 {
964            return Err(UiError::Capacity);
965        }
966        self.clips[self.clip_len] = self.clip().intersect(rect).unwrap_or(UiRect {
967            min: [0.; 2],
968            size: [0.; 2],
969        });
970        self.clip_len += 1;
971        Ok(())
972    }
973    pub fn pop_clip(&mut self) {
974        self.clip_len = self.clip_len.saturating_sub(1).max(1);
975    }
976    fn clip(&self) -> UiRect {
977        self.clips[self.clip_len - 1]
978    }
979    fn reserve(&self, rect: UiRect, vertices: usize) -> Result<(), UiError> {
980        if !rect.valid() {
981            return Err(UiError::InvalidLayout);
982        }
983        if self.commands.len() == 1024 || vertices > 196608 - self.vertices {
984            return Err(UiError::Capacity);
985        }
986        Ok(())
987    }
988    pub fn panel(&mut self, rect: UiRect, color: Color) -> Result<(), UiError> {
989        self.reserve(rect, 6)?;
990        if !valid_color(color) {
991            return Err(UiError::InvalidLayout);
992        }
993        self.commands.push(Command {
994            rect,
995            clip: self.clip(),
996            kind: Kind::Panel(color),
997        });
998        self.vertices += 6;
999        Ok(())
1000    }
1001    /// Horizontal color/alpha gradient; clipping preserves the original interpolation.
1002    pub fn gradient(&mut self, rect: UiRect, left: Color, right: Color) -> Result<(), UiError> {
1003        self.reserve(rect, 6)?;
1004        if !valid_color(left) || !valid_color(right) {
1005            return Err(UiError::InvalidLayout);
1006        }
1007        self.commands.push(Command {
1008            rect,
1009            clip: self.clip(),
1010            kind: Kind::Gradient(left, right),
1011        });
1012        self.vertices += 6;
1013        Ok(())
1014    }
1015    /// Format directly into the persistent UTF-8 arena; no temporary String.
1016    pub fn text_fmt(
1017        &mut self,
1018        rect: UiRect,
1019        style: TextStyle,
1020        args: fmt::Arguments<'_>,
1021    ) -> Result<(), UiError> {
1022        if !valid_text(style) {
1023            return Err(UiError::InvalidLayout);
1024        }
1025        self.reserve(rect, 0)?;
1026        let start = self.text.len();
1027        if (Arena(&mut self.text)).write_fmt(args).is_err() {
1028            self.text.truncate(start);
1029            return Err(UiError::Capacity);
1030        }
1031        let vertices = self.text[start..].chars().count() * 126 * if style.shadow { 2 } else { 1 };
1032        if let Err(e) = self.reserve(rect, vertices) {
1033            self.text.truncate(start);
1034            return Err(e);
1035        }
1036        self.commands.push(Command {
1037            rect,
1038            clip: self.clip(),
1039            kind: Kind::Text(start..self.text.len(), style, LineLimit::Unlimited),
1040        });
1041        self.vertices += vertices;
1042        Ok(())
1043    }
1044    pub fn text(&mut self, rect: UiRect, text: &str, style: TextStyle) -> Result<(), UiError> {
1045        self.text_fmt(rect, style, format_args!("{text}"))
1046    }
1047    /// Queue measured word-wrapped copy at fixed `style.size`, with an explicit
1048    /// line limit. `style.wrap` is ignored; color, alignment and shadow are kept.
1049    /// The returned metrics match [`WrappedText::measure`] before geometric
1050    /// clipping: `rect` and the current clip can still cut a partial last line.
1051    /// Use the measured `height` for a content-sized block, or a line limit of
1052    /// `floor(rect.size[1] / style.size)` to keep complete line slots in a card.
1053    ///
1054    /// The full source is copied into the existing 32 KiB arena, even when lines
1055    /// are hidden. Only retained glyphs (including the suffix) reserve vertices.
1056    /// Invalid styles/rectangles or exhausted budgets reject the whole command;
1057    /// an empty/zero-line block still uses one command, like [`Self::text`].
1058    ///
1059    /// ```
1060    /// use ferravex_render::ui::{TextStyle, Ui, UiRect, Viewport};
1061    /// use ferravex_render::ui::text_layout::LineLimit;
1062    /// let mut ui = Ui::new();
1063    /// ui.begin(Viewport::responsive([320., 240.], [0.; 4])?);
1064    /// let report = ui.wrapped_text(
1065    ///     UiRect { min: [16., 24.], size: [288., 36.] },
1066    ///     "BRIEFING\nCollect the keys.\nReturn to the gate.",
1067    ///     TextStyle::default(), LineLimit::Ellipsis(2),
1068    /// )?;
1069    /// assert_eq!((report.visible_lines, report.hidden_lines), (2, 1));
1070    /// assert!(report.is_truncated());
1071    /// ui.paint();
1072    /// # Ok::<(), ferravex_render::ui::UiError>(())
1073    /// ```
1074    pub fn wrapped_text(
1075        &mut self,
1076        rect: UiRect,
1077        text: &str,
1078        style: TextStyle,
1079        limit: LineLimit,
1080    ) -> Result<TextBlockMetrics, UiError> {
1081        if !valid_text(style) {
1082            return Err(UiError::InvalidLayout);
1083        }
1084        self.reserve(rect, 0)?;
1085        if text.len() > 32768 - self.text.len() {
1086            return Err(UiError::Capacity);
1087        }
1088        let layout = WrappedText::new(text, rect.size[0], style.size)?.with_limit(limit);
1089        let measured = layout.measure();
1090        let glyphs = layout
1091            .lines()
1092            .map(|line| line.text.chars().count() + line.suffix.len())
1093            .sum::<usize>();
1094        let vertices = glyphs * 126 * if style.shadow { 2 } else { 1 };
1095        self.reserve(rect, vertices)?;
1096        let start = self.text.len();
1097        self.text.push_str(text);
1098        self.commands.push(Command {
1099            rect,
1100            clip: self.clip(),
1101            kind: Kind::Text(
1102                start..self.text.len(),
1103                TextStyle {
1104                    wrap: true,
1105                    ..style
1106                },
1107                limit,
1108            ),
1109        });
1110        self.vertices += vertices;
1111        Ok(measured)
1112    }
1113    /// A single-line HUD label that keeps `style.size` and ellipsizes overflow.
1114    /// Alignment and shadow are honored; `wrap` is ignored. Newlines truncate.
1115    /// The visible prefix is copied directly into the reusable text arena, so
1116    /// even a very long source label consumes only its visible text budget.
1117    /// Use [`Viewport::responsive`] to keep this size in host logical pixels.
1118    ///
1119    /// ```
1120    /// use ferravex_render::ui::{Anchor, TextStyle, Ui, Viewport};
1121    /// let mut ui = Ui::new(); // Keep this outside the frame loop.
1122    /// let viewport = Viewport::responsive([320., 240.], [0., 20., 0., 0.])?;
1123    /// ui.begin(viewport);
1124    /// let score = Anchor::TopRight.place(viewport.bounds().inset([12.; 4])?, [180., 24.])?;
1125    /// ui.label(score, "COLLECT THE REMAINING CRYSTALS", TextStyle::default())?;
1126    /// # Ok::<(), ferravex_render::ui::UiError>(())
1127    /// ```
1128    pub fn label(&mut self, rect: UiRect, text: &str, style: TextStyle) -> Result<(), UiError> {
1129        if !valid_text(style) {
1130            return Err(UiError::InvalidLayout);
1131        }
1132        let label = fit_label(text, rect.size[0], style.size * 0.75)?;
1133        self.text_fmt(
1134            rect,
1135            TextStyle {
1136                wrap: false,
1137                ..style
1138            },
1139            format_args!("{}{}", label.prefix, label.suffix),
1140        )?;
1141        self.inspect_full_label(text, label.prefix.len() != text.len());
1142        Ok(())
1143    }
1144    /// A button with an ellipsized, fixed-size label and the same clipped
1145    /// hit/focus rectangle as [`Self::button`]. Eight logical pixels on each side
1146    /// are reserved for padding; on tiny rectangles text clips to the button.
1147    /// The full label is retained only when inspection is opted in and its
1148    /// separate bounded arena has room; otherwise hosts keep accessibility copy.
1149    ///
1150    /// ```
1151    /// use ferravex_render::ui::{ButtonStyle, Ui, Viewport, hud_slots};
1152    /// let mut ui = Ui::new(); // Reuse between frames.
1153    /// let viewport = Viewport::responsive([320., 240.], [0.; 4])?;
1154    /// ui.begin(viewport);
1155    /// let labels = ["RESUME EXPEDITION", "RESTART FROM CHECKPOINT", "QUIT"];
1156    /// // Two 144px columns; the third action wraps, retaining a 44px row height.
1157    /// for (index, rect) in hud_slots(viewport.bounds().inset([12.; 4])?, 3, 140., 44., 8.)?.enumerate() {
1158    ///     ui.hud_button(index as u64, rect, labels[index], true, ButtonStyle::default())?;
1159    /// }
1160    /// # Ok::<(), ferravex_render::ui::UiError>(())
1161    /// ```
1162    pub fn hud_button(
1163        &mut self,
1164        id: WidgetId,
1165        rect: UiRect,
1166        text: &str,
1167        enabled: bool,
1168        style: ButtonStyle,
1169    ) -> Result<(), UiError> {
1170        let label = fit_label(text, (rect.size[0] - 16.).max(0.), style.size * 0.75)?;
1171        self.queue_button(id, rect, [label.prefix, label.suffix], enabled, style)?;
1172        self.inspect_full_label(text, label.prefix.len() != text.len());
1173        Ok(())
1174    }
1175    pub fn button(
1176        &mut self,
1177        id: WidgetId,
1178        rect: UiRect,
1179        text: &str,
1180        enabled: bool,
1181        style: ButtonStyle,
1182    ) -> Result<(), UiError> {
1183        self.queue_button(id, rect, [text, ""], enabled, style)
1184    }
1185    fn queue_button(
1186        &mut self,
1187        id: WidgetId,
1188        rect: UiRect,
1189        text: [&str; 2],
1190        enabled: bool,
1191        style: ButtonStyle,
1192    ) -> Result<(), UiError> {
1193        let vertices = text.iter().map(|part| part.chars().count()).sum::<usize>() * 126 + 30;
1194        self.reserve(rect, vertices)?;
1195        if !valid_color(style.fill)
1196            || !valid_color(style.ink)
1197            || !valid_color(style.focus)
1198            || !valid_color(style.disabled)
1199            || !style.size.is_finite()
1200            || !(1. ..=256.).contains(&style.size)
1201        {
1202            return Err(UiError::InvalidLayout);
1203        }
1204        if text.iter().map(|part| part.len()).sum::<usize>() > 32768 - self.text.len() {
1205            return Err(UiError::Capacity);
1206        }
1207        self.state.add(Widget {
1208            id,
1209            rect,
1210            clip: Some(self.clip()),
1211            enabled,
1212            focusable: true,
1213        })?;
1214        let start = self.text.len();
1215        for part in text {
1216            self.text.push_str(part);
1217        }
1218        self.commands.push(Command {
1219            rect,
1220            clip: self.clip(),
1221            kind: Kind::Button(id, start..self.text.len(), style, enabled),
1222        });
1223        self.vertices += vertices;
1224        Ok(())
1225    }
1226    /// Finish layout before input. Block while the host's settings editor is open.
1227    /// Keyboard Tab/arrows/Enter, gamepad D-pad/A and one captured touch are supported.
1228    /// Include a player's remapped global confirm action and selected gamepad.
1229    pub fn finish_player(&mut self, player: &mut crate::input::PlayerInput, enabled: bool) {
1230        let accept = enabled && player.pressed("confirm");
1231        self.finish_with_gamepad(enabled, player.settings().gamepad);
1232        if accept
1233            && !player.controls_open()
1234            && crate::read(|s| s.input.focused && !s.input.overflow && !s.controls_open)
1235        {
1236            self.interaction.player_confirmed = self.accept().or(self.interaction.player_confirmed);
1237        }
1238    }
1239    pub fn finish(&mut self, enabled: bool) {
1240        self.finish_with_gamepad(enabled, 0);
1241    }
1242    /// Use the player profile’s selected pad (0..4).
1243    pub fn finish_with_gamepad(&mut self, enabled: bool, pad: u8) {
1244        self.state.end_frame();
1245        self.hovered = None;
1246        let mut events = [PlatformEvent::None; crate::input::MAX_EVENTS];
1247        let (frame, epoch, focused, overflow, blocked, pointer, pad_epoch) = crate::read(|s| {
1248            let source = s.input.events();
1249            events[..source.len()].copy_from_slice(source);
1250            (
1251                s.frame,
1252                s.input.focus_epoch,
1253                s.input.focused,
1254                s.input.overflow,
1255                s.controls_open,
1256                [s.mouse.x, s.mouse.y],
1257                s.input
1258                    .pads
1259                    .get(pad as usize)
1260                    .filter(|p| p.connected)
1261                    .map(|p| (pad, p.epoch)),
1262            )
1263        });
1264        let fresh_pad = self.pad_epoch != pad_epoch;
1265        self.pad_epoch = pad_epoch;
1266        if self.frame != Some(frame) {
1267            self.interaction = UiInteraction {
1268                pointer_consumed: self.owned_pointer.is_some(),
1269                pointer_capture: self.owned_pointer.map(|(_, id)| id),
1270                ..Default::default()
1271            };
1272        }
1273        self.interaction.input_blocked |= blocked || !focused || overflow;
1274        if epoch != self.epoch || !focused || overflow {
1275            self.shift = 0;
1276        }
1277        if epoch != self.epoch || !focused || overflow || !enabled || blocked {
1278            self.cancel();
1279        }
1280        if epoch != self.epoch || !focused || overflow {
1281            self.owned_pointer = None;
1282            self.interaction.pointer_capture = None;
1283        }
1284        self.epoch = epoch;
1285        if self.frame == Some(frame) {
1286            return;
1287        }
1288        self.frame = Some(frame);
1289        let interactive = enabled && !blocked && focused && !overflow;
1290        if interactive {
1291            self.hovered = self
1292                .viewport
1293                .unproject(pointer)
1294                .and_then(|p| self.state.hit_test(p));
1295        }
1296        let mut event_pointer = pointer;
1297        for event in events {
1298            if matches!(event, PlatformEvent::None) {
1299                break;
1300            }
1301            // A cancelled/removed widget still owns its gesture's release.
1302            // Observe terminal events even when UI is disabled or Controls open.
1303            let ended = match (self.owned_pointer, event) {
1304                (Some((OwnedPointer::Mouse, _)), PlatformEvent::Value(InputCode::Mouse(1), v)) => {
1305                    v < 0.5
1306                }
1307                (Some((OwnedPointer::Touch(id), _)), PlatformEvent::Touch(e)) => {
1308                    e.id == id && matches!(e.phase, touch::Phase::End | touch::Phase::Cancel)
1309                }
1310                _ => false,
1311            };
1312            if ended {
1313                self.interaction.pointer_consumed = true;
1314                self.owned_pointer = None;
1315            }
1316            if !interactive {
1317                continue;
1318            }
1319            match event {
1320                PlatformEvent::PointerPosition(p) => event_pointer = [p.x, p.y],
1321                PlatformEvent::Value(InputCode::Mouse(1), v) if self.touch.is_none() => {
1322                    let p = self
1323                        .viewport
1324                        .unproject(event_pointer)
1325                        .unwrap_or([f32::NEG_INFINITY; 2]);
1326                    if v >= 0.5 {
1327                        if self.owned_pointer.is_none() {
1328                            self.mouse_capture = true;
1329                            self.own_pointer(OwnedPointer::Mouse, p);
1330                            self.state.pointer_down(p);
1331                        }
1332                    } else if self.mouse_capture {
1333                        self.mouse_capture = false;
1334                        self.pointer_up(p);
1335                    }
1336                }
1337                PlatformEvent::Touch(e) => {
1338                    let p = self
1339                        .viewport
1340                        .unproject([e.position.x, e.position.y])
1341                        .unwrap_or([f32::NEG_INFINITY; 2]);
1342                    match e.phase {
1343                        touch::Phase::Start
1344                            if self.touch.is_none()
1345                                && !self.mouse_capture
1346                                && self.owned_pointer.is_none() =>
1347                        {
1348                            self.touch = Some(e.id);
1349                            self.own_pointer(OwnedPointer::Touch(e.id), p);
1350                            self.state.pointer_down(p);
1351                        }
1352                        touch::Phase::End if self.touch == Some(e.id) => {
1353                            self.touch = None;
1354                            self.pointer_up(p);
1355                        }
1356                        touch::Phase::Cancel if self.touch == Some(e.id) => self.cancel(),
1357                        _ => {}
1358                    }
1359                }
1360                PlatformEvent::Value(InputCode::Key(key), v) if key == 0xffe1 || key == 0xffe2 => {
1361                    let bit = if key == 0xffe1 { 1 } else { 2 };
1362                    if v >= 0.5 {
1363                        self.shift |= bit;
1364                    } else {
1365                        self.shift &= !bit;
1366                    }
1367                }
1368                PlatformEvent::Value(InputCode::Key(key), v) if v >= 0.5 => match key {
1369                    0xff09 => {
1370                        self.state.focus_next(self.shift != 0);
1371                    }
1372                    0xff54 | 0xff53 => {
1373                        self.state.focus_next(false);
1374                    }
1375                    0xff52 | 0xff51 => {
1376                        self.state.focus_next(true);
1377                    }
1378                    0xff0d => {
1379                        self.interaction.keyboard_confirmed =
1380                            self.accept().or(self.interaction.keyboard_confirmed);
1381                    }
1382                    0xff1b => self.cancel(),
1383                    _ => {}
1384                },
1385                PlatformEvent::Pad {
1386                    index,
1387                    code: InputCode::PadButton(b),
1388                    value,
1389                } if index == pad && !fresh_pad && value >= 0.5 => match b {
1390                    12 | 14 => {
1391                        self.state.focus_next(true);
1392                    }
1393                    13 | 15 => {
1394                        self.state.focus_next(false);
1395                    }
1396                    0 => {
1397                        self.interaction.gamepad_confirmed =
1398                            self.accept().or(self.interaction.gamepad_confirmed);
1399                    }
1400                    _ => {}
1401                },
1402                _ => {}
1403            }
1404        }
1405        self.interaction.pointer_capture = self.owned_pointer.map(|(_, id)| id);
1406    }
1407    fn accept(&mut self) -> Option<WidgetId> {
1408        if self.auto_focus && self.state.focused().is_none() {
1409            self.state.focus_next(false);
1410        }
1411        let accepted = self.state.activate_focused();
1412        self.active = accepted.or(self.active);
1413        accepted
1414    }
1415    /// Append unlit clip-space geometry in paint order, independent of the world camera.
1416    pub fn paint(&self) {
1417        crate::edit(|s| {
1418            if s.w == 0 || s.h == 0 {
1419                return;
1420            }
1421            let start = s.vertices.len() as u32;
1422            let mut painter = Painter {
1423                vertices: &mut s.vertices,
1424                viewport: self.viewport,
1425                screen: [s.w as f32, s.h as f32],
1426            };
1427            for c in &self.commands {
1428                match &c.kind {
1429                    Kind::Panel(color) => painter.rect(c.rect, c.clip, *color),
1430                    Kind::Gradient(left, right) => painter.gradient(c.rect, c.clip, *left, *right),
1431                    Kind::Text(range, style, limit) => {
1432                        painter.text(c.rect, c.clip, &self.text[range.clone()], *style, *limit)
1433                    }
1434                    Kind::Button(id, range, style, enabled) => {
1435                        let Some(clip) = c.rect.intersect(c.clip) else {
1436                            continue;
1437                        };
1438                        painter.rect(
1439                            c.rect,
1440                            clip,
1441                            if *enabled { style.fill } else { style.disabled },
1442                        );
1443                        if *enabled
1444                            && (self.state.focused() == Some(*id) || self.hovered == Some(*id))
1445                        {
1446                            let r = c.rect;
1447                            let border = 2_f32.min(r.size[0]).min(r.size[1]);
1448                            for edge in [
1449                                UiRect {
1450                                    min: r.min,
1451                                    size: [r.size[0], border],
1452                                },
1453                                UiRect {
1454                                    min: [r.min[0], r.min[1] + r.size[1] - border],
1455                                    size: [r.size[0], border],
1456                                },
1457                                UiRect {
1458                                    min: r.min,
1459                                    size: [border, r.size[1]],
1460                                },
1461                                UiRect {
1462                                    min: [r.min[0] + r.size[0] - border, r.min[1]],
1463                                    size: [border, r.size[1]],
1464                                },
1465                            ] {
1466                                painter.rect(edge, clip, style.focus);
1467                            }
1468                        }
1469                        let rect = UiRect {
1470                            min: [
1471                                c.rect.min[0] + 8.,
1472                                c.rect.min[1] + (c.rect.size[1] - style.size * 0.875) * 0.5,
1473                            ],
1474                            size: [(c.rect.size[0] - 16.).max(0.), style.size],
1475                        };
1476                        painter.text(
1477                            rect,
1478                            clip,
1479                            &self.text[range.clone()],
1480                            TextStyle {
1481                                size: style.size,
1482                                color: style.ink,
1483                                align: Align::Center,
1484                                ..Default::default()
1485                            },
1486                            LineLimit::Unlimited,
1487                        );
1488                    }
1489                }
1490            }
1491            let count = s.vertices.len() as u32 - start;
1492            if count > 0 {
1493                s.record_immediate(start, count, false);
1494            }
1495        });
1496    }
1497}
1498struct InspectionCount(usize);
1499impl Write for InspectionCount {
1500    fn write_str(&mut self, text: &str) -> fmt::Result {
1501        self.0 += text.len();
1502        Ok(())
1503    }
1504}
1505struct InspectionOutput<'a> {
1506    bytes: &'a mut [u8],
1507    len: usize,
1508}
1509impl Write for InspectionOutput<'_> {
1510    fn write_str(&mut self, text: &str) -> fmt::Result {
1511        let end = self.len + text.len();
1512        let dest = self.bytes.get_mut(self.len..end).ok_or(fmt::Error)?;
1513        dest.copy_from_slice(text.as_bytes());
1514        self.len = end;
1515        Ok(())
1516    }
1517}
1518fn inspection_json_string(out: &mut impl Write, text: &str) -> fmt::Result {
1519    out.write_char('"')?;
1520    for c in text.chars() {
1521        match c {
1522            '"' => out.write_str("\\\"")?,
1523            '\\' => out.write_str("\\\\")?,
1524            c if c <= '\u{1f}' => write!(out, "\\u{:04x}", c as u32)?,
1525            c => out.write_char(c)?,
1526        }
1527    }
1528    out.write_char('"')
1529}
1530fn inspection_json_rect(out: &mut impl Write, rect: Option<UiRect>) -> fmt::Result {
1531    match rect {
1532        Some(r) => write!(
1533            out,
1534            "[{},{},{},{}]",
1535            r.min[0], r.min[1], r.size[0], r.size[1]
1536        ),
1537        None => out.write_str("null"),
1538    }
1539}
1540fn write_inspection_json(elements: UiInspection<'_>, out: &mut impl Write) -> fmt::Result {
1541    out.write_str("{\"schema\":1,\"elements\":[")?;
1542    for (i, e) in elements.enumerate() {
1543        if i != 0 {
1544            out.write_char(',')?;
1545        }
1546        out.write_str("{\"id\":")?;
1547        match e.id {
1548            Some(id) => write!(out, "\"{id}\"")?,
1549            None => out.write_str("null")?,
1550        }
1551        out.write_str(",\"role\":")?;
1552        inspection_json_string(
1553            out,
1554            match e.role {
1555                UiRole::Panel => "panel",
1556                UiRole::Gradient => "gradient",
1557                UiRole::Text => "text",
1558                UiRole::Button => "button",
1559                UiRole::ModalBlocker => "modal_blocker",
1560            },
1561        )?;
1562        out.write_str(",\"label\":")?;
1563        match e.label {
1564            UiLabel::Full(text) => inspection_json_string(out, text)?,
1565            UiLabel::Unavailable { .. } => out.write_str("null")?,
1566        }
1567        if let UiLabel::Unavailable { required_bytes } = e.label {
1568            write!(out, ",\"label_required_bytes\":{required_bytes}")?;
1569        }
1570        out.write_str(",\"painted_label\":")?;
1571        inspection_json_string(out, e.painted_label)?;
1572        out.write_str(",\"bounds\":")?;
1573        inspection_json_rect(out, Some(e.bounds))?;
1574        out.write_str(",\"visible_bounds\":")?;
1575        inspection_json_rect(out, e.visible_bounds)?;
1576        write!(
1577            out,
1578            ",\"enabled\":{},\"focused\":{},\"interaction_registered\":{}}}",
1579            e.enabled, e.focused, e.interaction_registered
1580        )?;
1581    }
1582    out.write_str("]}")
1583}
1584fn valid_color(c: Color) -> bool {
1585    [c.r, c.g, c.b, c.a].into_iter().all(f32::is_finite)
1586}
1587fn valid_text(s: TextStyle) -> bool {
1588    s.size.is_finite() && (1. ..=256.).contains(&s.size) && valid_color(s.color)
1589}
1590struct Arena<'a>(&'a mut String);
1591impl Write for Arena<'_> {
1592    fn write_str(&mut self, s: &str) -> fmt::Result {
1593        if s.len() > 32768 - self.0.len() {
1594            return Err(fmt::Error);
1595        }
1596        self.0.push_str(s);
1597        Ok(())
1598    }
1599}
1600struct Painter<'a> {
1601    vertices: &'a mut Vec<[f32; 8]>,
1602    viewport: Viewport,
1603    screen: [f32; 2],
1604}
1605impl Painter<'_> {
1606    fn rect(&mut self, r: UiRect, clip: UiRect, color: Color) {
1607        if let Some(r) = r.intersect(clip) {
1608            self.quad(r, color, color);
1609        }
1610    }
1611    fn gradient(&mut self, original: UiRect, clip: UiRect, left: Color, right: Color) {
1612        let Some(r) = original.intersect(clip) else {
1613            return;
1614        };
1615        let color = |x: f32| {
1616            let t = ((x - original.min[0]) / original.size[0]).clamp(0., 1.) as f64;
1617            let mix = |a: f32, b: f32| ((a as f64) * (1. - t) + (b as f64) * t) as f32;
1618            Color::new(
1619                mix(left.r, right.r),
1620                mix(left.g, right.g),
1621                mix(left.b, right.b),
1622                mix(left.a, right.a),
1623            )
1624        };
1625        self.quad(r, color(r.min[0]), color(r.min[0] + r.size[0]));
1626    }
1627    fn quad(&mut self, r: UiRect, left: Color, right: Color) {
1628        let point = |x: f32, y: f32, c: Color| {
1629            let px = self.viewport.pixels().min[0] + x * self.viewport.scale();
1630            let py = self.viewport.pixels().min[1] + y * self.viewport.scale();
1631            [
1632                px / self.screen[0] * 2. - 1.,
1633                1. - py / self.screen[1] * 2.,
1634                0.,
1635                1.,
1636                c.r,
1637                c.g,
1638                c.b,
1639                c.a,
1640            ]
1641        };
1642        let [x, y] = r.min;
1643        let [w, h] = r.size;
1644        self.vertices.extend_from_slice(&[
1645            point(x, y, left),
1646            point(x + w, y, right),
1647            point(x + w, y + h, right),
1648            point(x, y, left),
1649            point(x + w, y + h, right),
1650            point(x, y + h, left),
1651        ]);
1652    }
1653    fn text(&mut self, r: UiRect, clip: UiRect, text: &str, style: TextStyle, limit: LineLimit) {
1654        let Some(clip) = r.intersect(clip) else {
1655            return;
1656        };
1657        // Fixed bitmap metrics, UTF-8 boundaries and word wrapping preserve readable copy.
1658        // Unsupported glyphs use '?' rather than silently disappearing.
1659        let max_columns = text
1660            .split('\n')
1661            .map(|l| l.chars().count())
1662            .max()
1663            .unwrap_or(0)
1664            .max(1);
1665        let size = if style.wrap {
1666            style.size
1667        } else {
1668            style.size.min(r.size[0] * 8. / (max_columns as f32 * 6.))
1669        };
1670        if size <= 0. {
1671            return;
1672        }
1673        let cell = size / 8.;
1674        let advance = 6. * cell;
1675        let columns = (r.size[0] / advance).floor() as usize;
1676        let lines = WrappedLines::new(
1677            text,
1678            if style.wrap { columns } else { usize::MAX },
1679            columns,
1680            advance,
1681            limit,
1682        );
1683        for (line_index, line) in lines.enumerate() {
1684            let y = r.min[1] + line_index as f32 * size;
1685            if y >= r.min[1] + r.size[1] {
1686                break;
1687            }
1688            let width = line.width;
1689            let x = r.min[0]
1690                + match style.align {
1691                    Align::Left => 0.,
1692                    Align::Center => (r.size[0] - width) * 0.5,
1693                    Align::Right => r.size[0] - width,
1694                };
1695            for (index, c) in line.text.chars().chain(line.suffix.chars()).enumerate() {
1696                let c = c.to_ascii_uppercase();
1697                let glyph = crate::font::glyph(if c == ' ' || crate::font::glyph(c) != [0; 7] {
1698                    c
1699                } else {
1700                    '?'
1701                });
1702                for (row, bits) in glyph.into_iter().enumerate() {
1703                    let mut col = 0;
1704                    while col < 5 {
1705                        if bits & (1 << (4 - col)) == 0 {
1706                            col += 1;
1707                            continue;
1708                        }
1709                        let start = col;
1710                        while col < 5 && bits & (1 << (4 - col)) != 0 {
1711                            col += 1;
1712                        }
1713                        let rect = UiRect {
1714                            min: [
1715                                x + index as f32 * advance + start as f32 * cell,
1716                                y + row as f32 * cell,
1717                            ],
1718                            size: [(col - start) as f32 * cell, cell],
1719                        };
1720                        if style.shadow {
1721                            self.rect(
1722                                UiRect {
1723                                    min: [rect.min[0] + cell * 0.5, rect.min[1] + cell * 0.5],
1724                                    ..rect
1725                                },
1726                                clip,
1727                                Color::new(0., 0., 0., 0.7),
1728                            );
1729                        }
1730                        self.rect(rect, clip, style.color);
1731                    }
1732                }
1733            }
1734        }
1735    }
1736}
1737#[cfg(test)]
1738mod tests {
1739    use super::super::text_layout::Lines;
1740    use super::*;
1741    const RECT: UiRect = UiRect {
1742        min: [20.; 2],
1743        size: [80., 40.],
1744    };
1745    fn reset() {
1746        crate::edit(|s| *s = crate::State::default());
1747    }
1748    fn next() {
1749        crate::edit(|s| {
1750            s.frame += 1;
1751            s.input.finish_frame();
1752            s.vertices.clear();
1753            s.batches.clear();
1754            s.retained.commands.clear();
1755        });
1756    }
1757    fn begin(ui: &mut Ui) {
1758        ui.begin(Viewport::fit([200.; 2], [200.; 2], [0.; 4]).unwrap());
1759    }
1760    fn button(ui: &mut Ui, id: u64, enabled: bool) {
1761        ui.button(id, RECT, "PLAY", enabled, ButtonStyle::default())
1762            .unwrap();
1763    }
1764    #[derive(Debug, PartialEq)]
1765    struct CompositionSnapshot {
1766        commands: usize,
1767        text: String,
1768        vertices: usize,
1769        clips: [UiRect; 16],
1770        clip_len: usize,
1771        modal: (usize, Option<WidgetId>),
1772        inspection: Option<(usize, String, bool, Vec<u8>)>,
1773        focus_capture: (Option<WidgetId>, Option<WidgetId>),
1774        interaction: UiInteraction,
1775        active_hover: (Option<WidgetId>, Option<WidgetId>),
1776        owner: Option<(Option<u64>, WidgetId)>,
1777        input: (Option<u64>, Option<u64>, u64, u8, bool),
1778        hits: Vec<Option<WidgetId>>,
1779        paint: Vec<[f32; 8]>,
1780        reserved: usize,
1781    }
1782    fn composition_snapshot(ui: &Ui) -> CompositionSnapshot {
1783        let inspection = ui.inspection.as_ref().map(|storage| {
1784            let mut bytes = vec![0; 512 * 1024];
1785            if storage.active {
1786                let n = ui.write_inspection(&mut bytes).unwrap();
1787                bytes.truncate(n);
1788            } else {
1789                bytes.clear();
1790            }
1791            (
1792                storage.labels.len(),
1793                storage.text.clone(),
1794                storage.active,
1795                bytes,
1796            )
1797        });
1798        crate::edit(|s| {
1799            s.vertices.clear();
1800            s.batches.clear();
1801            s.retained.commands.clear();
1802        });
1803        ui.paint();
1804        CompositionSnapshot {
1805            commands: ui.commands.len(),
1806            text: ui.text.clone(),
1807            vertices: ui.vertices,
1808            clips: ui.clips,
1809            clip_len: ui.clip_len,
1810            modal: (ui.modal_start, ui.modal_blocker),
1811            inspection,
1812            focus_capture: (ui.state.focused(), ui.state.captured()),
1813            interaction: ui.interaction(),
1814            active_hover: (ui.active, ui.hovered),
1815            owner: ui.owned_pointer.map(|(p, id)| {
1816                (
1817                    match p {
1818                        OwnedPointer::Mouse => None,
1819                        OwnedPointer::Touch(id) => Some(id),
1820                    },
1821                    id,
1822                )
1823            }),
1824            input: (ui.touch, ui.frame, ui.epoch, ui.shift, ui.mouse_capture),
1825            hits: (0..20)
1826                .flat_map(|y| {
1827                    (0..20).map(move |x| {
1828                        ui.state
1829                            .hit_test([x as f32 * 10. + 5., y as f32 * 10. + 5.])
1830                    })
1831                })
1832                .collect(),
1833            paint: crate::read(|s| s.vertices.clone()),
1834            reserved: ui.reserved_bytes(),
1835        }
1836    }
1837    fn composition_prior() -> Ui {
1838        reset();
1839        let mut ui = Ui::new();
1840        ui.set_inspection_enabled(true);
1841        begin(&mut ui);
1842        button(&mut ui, 1, true);
1843        ui.modal(90).unwrap();
1844        ui.hud_button(
1845            2,
1846            RECT,
1847            "PRIOR FOCUSED FULL LABEL é",
1848            true,
1849            ButtonStyle::default(),
1850        )
1851        .unwrap();
1852        crate::pointer(30., 30., 0., 0.);
1853        crate::button(1, true);
1854        ui.finish(true);
1855        assert_eq!(ui.state.focused(), Some(2));
1856        assert_eq!(ui.state.captured(), Some(2));
1857        assert_eq!(ui.interaction().pointer_capture, Some(2));
1858        ui.push_clip(UiRect {
1859            min: [10.; 2],
1860            size: [150.; 2],
1861        })
1862        .unwrap();
1863        ui
1864    }
1865    fn composition_part(
1866        group: &mut UiComposition<'_>,
1867        part: usize,
1868        bad: bool,
1869    ) -> Result<(), UiError> {
1870        composition_part_at(group, part, RECT, bad)
1871    }
1872    fn composition_part_at(
1873        group: &mut UiComposition<'_>,
1874        part: usize,
1875        rect: UiRect,
1876        bad: bool,
1877    ) -> Result<(), UiError> {
1878        let color = if bad {
1879            Color::new(f32::NAN, 0., 0., 1.)
1880        } else {
1881            INK
1882        };
1883        let text = TextStyle {
1884            color,
1885            ..Default::default()
1886        };
1887        let button = ButtonStyle {
1888            disabled: color,
1889            ..Default::default()
1890        };
1891        match part {
1892            0 => group.panel(rect, color),
1893            1 => group.gradient(rect, PANEL, color),
1894            2 => group.text_fmt(rect, text, format_args!("{}", "Ω")),
1895            3 => group.text(rect, "TEXT", text),
1896            4 => group
1897                .wrapped_text(rect, "WRAPPED", text, LineLimit::Clip(2))
1898                .map(|_| ()),
1899            5 => group.label(rect, "FULL LABEL é TO RETAIN", text),
1900            6 => group.button(106, rect, "OK", true, button),
1901            7 => group.hud_button(107, rect, "FULL BUTTON LABEL TO RETAIN", true, button),
1902            8 => group.button_with_options(
1903                108,
1904                rect,
1905                "OK",
1906                super::super::ButtonOptions {
1907                    selected: true,
1908                    ..Default::default()
1909                },
1910                button,
1911            ),
1912            9 => group.hud_button_with_options(
1913                109,
1914                rect,
1915                "FULL OPTION LABEL TO RETAIN",
1916                super::super::ButtonOptions {
1917                    enabled: false,
1918                    selected: true,
1919                },
1920                button,
1921            ),
1922            _ => unreachable!(),
1923        }
1924    }
1925    fn composition_parts(group: &mut UiComposition<'_>) -> Result<(), UiError> {
1926        group.modal(99)?;
1927        group.push_clip(RECT)?;
1928        for part in 0..10 {
1929            composition_part(group, part, false)?;
1930        }
1931        group.pop_clip()
1932    }
1933    #[test]
1934    fn journey400_281_every_constituent_command_vertex_and_text_budget_rolls_back() {
1935        // Measure each production submission's charge, then exhaust the actual
1936        // arenas at every constituent boundary (no budget fields are patched).
1937        let mut probe = composition_prior();
1938        let mut charges = [(0, 0); 10];
1939        probe
1940            .compose(|group| {
1941                for (part, charge) in charges.iter_mut().enumerate() {
1942                    let before = (group.ui.vertices, group.ui.text.len());
1943                    composition_part(group, part, false)?;
1944                    *charge = (group.ui.vertices - before.0, group.ui.text.len() - before.1);
1945                }
1946                Ok(())
1947            })
1948            .unwrap();
1949        for budget in 0..3 {
1950            for fail_at in 0..10 {
1951                if budget == 2 && charges[fail_at].1 == 0 {
1952                    continue;
1953                }
1954                let mut ui = composition_prior();
1955                match budget {
1956                    0 => {
1957                        while ui.commands.len() < 1024 - fail_at {
1958                            ui.panel(RECT, PANEL).unwrap();
1959                        }
1960                    }
1961                    1 => {
1962                        let remaining = charges[..=fail_at].iter().map(|c| c.0).sum::<usize>() - 6;
1963                        let fill = 196608 - ui.vertices - remaining;
1964                        ui.text(RECT, &"A".repeat(fill / 126), TextStyle::default())
1965                            .unwrap();
1966                        for _ in 0..(fill % 126) / 6 {
1967                            ui.panel(RECT, PANEL).unwrap();
1968                        }
1969                        assert_eq!(196608 - ui.vertices, remaining);
1970                    }
1971                    2 => {
1972                        let remaining = charges[..=fail_at].iter().map(|c| c.1).sum::<usize>() - 1;
1973                        let fill = "x".repeat(32768 - ui.text.len() - remaining);
1974                        ui.wrapped_text(RECT, &fill, TextStyle::default(), LineLimit::Clip(0))
1975                            .unwrap();
1976                    }
1977                    _ => unreachable!(),
1978                }
1979                let before = composition_snapshot(&ui);
1980                let mut reached = 0;
1981                assert_eq!(
1982                    ui.compose(|group| {
1983                        group.modal(99)?;
1984                        group.push_clip(RECT)?;
1985                        for part in 0..10 {
1986                            reached = part;
1987                            composition_part(group, part, false)?;
1988                        }
1989                        group.pop_clip()
1990                    }),
1991                    Err(UiError::Capacity),
1992                    "budget {budget}, constituent {fail_at}"
1993                );
1994                assert_eq!(reached, fail_at);
1995                assert_eq!(
1996                    composition_snapshot(&ui),
1997                    before,
1998                    "budget {budget}, constituent {fail_at}"
1999                );
2000                assert_eq!(ui.ownership_hit([30.; 2]), Some(2));
2001            }
2002        }
2003    }
2004    #[test]
2005    fn journey400_281_invalid_colors_layout_and_duplicate_ids_restore_everything() {
2006        for fail_at in 0..10 {
2007            let mut ui = composition_prior();
2008            let before = composition_snapshot(&ui);
2009            assert_eq!(
2010                ui.compose(|group| {
2011                    group.modal(99)?;
2012                    group.push_clip(RECT)?;
2013                    for part in 0..=fail_at {
2014                        composition_part(group, part, part == fail_at)?;
2015                    }
2016                    Ok(())
2017                }),
2018                Err(UiError::InvalidLayout)
2019            );
2020            assert_eq!(composition_snapshot(&ui), before);
2021        }
2022        for id in [99, 106, 107, 108, 109] {
2023            let mut ui = composition_prior();
2024            let before = composition_snapshot(&ui);
2025            assert_eq!(
2026                ui.compose(|group| {
2027                    composition_parts(group)?;
2028                    group.hud_button(id, RECT, "DUPLICATE", true, ButtonStyle::default())
2029                }),
2030                Err(UiError::DuplicateId)
2031            );
2032            assert_eq!(composition_snapshot(&ui), before);
2033        }
2034        for fail_at in 0..10 {
2035            for bad_rect in [
2036                UiRect {
2037                    min: [f32::INFINITY, 0.],
2038                    ..RECT
2039                },
2040                UiRect {
2041                    size: [-1., 10.],
2042                    ..RECT
2043                },
2044            ] {
2045                let mut ui = composition_prior();
2046                let before = composition_snapshot(&ui);
2047                assert_eq!(
2048                    ui.compose(|group| {
2049                        group.modal(99)?;
2050                        for part in 0..=fail_at {
2051                            composition_part_at(
2052                                group,
2053                                part,
2054                                if part == fail_at { bad_rect } else { RECT },
2055                                false,
2056                            )?;
2057                        }
2058                        Ok(())
2059                    }),
2060                    Err(UiError::InvalidLayout)
2061                );
2062                assert_eq!(composition_snapshot(&ui), before);
2063            }
2064        }
2065        // Each button variant rejects the current blocker ID before adding a
2066        // command, and rolls back the commands accepted earlier in the group.
2067        for fail_at in 6..10 {
2068            let mut ui = composition_prior();
2069            let before = composition_snapshot(&ui);
2070            let mut reached = 0;
2071            assert_eq!(
2072                ui.compose(|group| {
2073                    group.modal((100 + fail_at) as u64)?;
2074                    for part in 0..=fail_at {
2075                        reached = part;
2076                        composition_part(group, part, false)?;
2077                    }
2078                    Ok(())
2079                }),
2080                Err(UiError::DuplicateId)
2081            );
2082            assert_eq!(reached, fail_at);
2083            assert_eq!(composition_snapshot(&ui), before);
2084        }
2085        let mut ui = composition_prior();
2086        let before = composition_snapshot(&ui);
2087        // Ordinary duplicate against an existing scope, without modal replacement.
2088        assert_eq!(
2089            ui.compose(|group| {
2090                group.panel(RECT, PANEL)?;
2091                group.button(2, RECT, "DUPLICATE", true, ButtonStyle::default())
2092            }),
2093            Err(UiError::DuplicateId)
2094        );
2095        assert_eq!(composition_snapshot(&ui), before);
2096    }
2097    #[test]
2098    fn journey400_281_inspection_misses_modal_replacement_and_widget_capacity_restore() {
2099        let mut ui = composition_prior();
2100        let before = composition_snapshot(&ui);
2101        let huge = "é".repeat(16385);
2102        let full = "x".repeat(32768);
2103        assert_eq!(
2104            ui.compose(|group| {
2105                // Repeated destructive modal changes cannot accumulate an undo log.
2106                for id in 200..1400 {
2107                    group.modal(id)?;
2108                }
2109                group.label(RECT, &full, TextStyle::default())?;
2110                group.label(RECT, &huge, TextStyle::default())?; // Metadata-only miss.
2111                assert_eq!(
2112                    group.ui.inspection.as_ref().unwrap().text.len(),
2113                    before.inspection.as_ref().unwrap().1.len()
2114                ); // Full cannot fit either.
2115                group.modal(500)?;
2116                group.button(500, RECT, "BAD", true, ButtonStyle::default())
2117            }),
2118            Err(UiError::DuplicateId)
2119        );
2120        assert_eq!(composition_snapshot(&ui), before);
2121        ui.label(RECT, "NEW SHORTENED LABEL", TextStyle::default())
2122            .unwrap();
2123        assert_eq!(
2124            ui.inspect().unwrap().last().unwrap().label,
2125            UiLabel::Full("NEW SHORTENED LABEL")
2126        );
2127        // At widget capacity there is still one command slot: the modal blocker
2128        // uses a registration without using a paint command.
2129        let mut ui = composition_prior();
2130        begin(&mut ui);
2131        ui.modal(99).unwrap();
2132        for id in 1000..2022 {
2133            ui.button(id, RECT, "", true, ButtonStyle::default())
2134                .unwrap();
2135        }
2136        let before = composition_snapshot(&ui);
2137        assert_eq!(
2138            ui.compose(|group| {
2139                group.button(4000, RECT, "", true, ButtonStyle::default())?;
2140                assert_eq!(group.ui.commands.len(), 1023);
2141                let result = group.button(4001, RECT, "", true, ButtonStyle::default());
2142                assert_eq!(result, Err(UiError::Capacity));
2143                assert_eq!(group.ui.commands.len(), 1023); // Command budget still has room.
2144                result
2145            }),
2146            Err(UiError::Capacity)
2147        );
2148        assert_eq!(composition_snapshot(&ui), before);
2149        begin(&mut ui);
2150        assert_eq!(ui.inspect().unwrap().len(), 0);
2151        ui.compose(composition_parts).unwrap();
2152        assert!(ui.state.hit_test([30.; 2]).is_none()); // Top option is disabled.
2153        assert_eq!(ui.ownership_hit([30.; 2]), Some(109));
2154        assert_eq!(ui.state.hit_test([150.; 2]), Some(99));
2155    }
2156    #[test]
2157    fn journey400_281_clip_balance_nested_fallback_depth_and_sticky_errors() {
2158        let mut ui = composition_prior();
2159        let before = composition_snapshot(&ui);
2160        assert_eq!(
2161            ui.compose(|group| group.pop_clip()),
2162            Err(UiError::InvalidLayout)
2163        );
2164        assert_eq!(composition_snapshot(&ui), before);
2165        assert_eq!(
2166            ui.compose(|group| group.push_clip(RECT)),
2167            Err(UiError::InvalidLayout)
2168        );
2169        assert_eq!(composition_snapshot(&ui), before);
2170        assert_eq!(
2171            ui.compose(|group| {
2172                for _ in 0..16 {
2173                    group.push_clip(RECT)?;
2174                }
2175                Ok(())
2176            }),
2177            Err(UiError::Capacity)
2178        );
2179        assert_eq!(composition_snapshot(&ui), before);
2180        assert_eq!(
2181            ui.compose(|group| {
2182                group.push_clip(UiRect {
2183                    size: [f32::NAN, 1.],
2184                    ..RECT
2185                })
2186            }),
2187            Err(UiError::InvalidLayout)
2188        );
2189        assert_eq!(composition_snapshot(&ui), before);
2190        assert_eq!(
2191            ui.compose(|group| {
2192                let _ = group.button(2, RECT, "BAD", true, ButtonStyle::default());
2193                assert_eq!(group.panel(RECT, PANEL), Err(UiError::DuplicateId));
2194                let mut called = false;
2195                assert_eq!(
2196                    group.compose(|_| {
2197                        called = true;
2198                        Ok(())
2199                    }),
2200                    Err(UiError::DuplicateId)
2201                );
2202                assert!(!called);
2203                Ok(()) // Ignoring errors still rejects the group.
2204            }),
2205            Err(UiError::DuplicateId)
2206        );
2207        assert_eq!(composition_snapshot(&ui), before);
2208        // Successful inner work is still rolled back by outer callback error.
2209        assert_eq!(
2210            ui.compose(|group| {
2211                group.compose(composition_parts)?;
2212                Err::<(), _>(UiError::InvalidLayout)
2213            }),
2214            Err(UiError::InvalidLayout)
2215        );
2216        assert_eq!(composition_snapshot(&ui), before);
2217        // A child cannot pop its parent's clip; the parent can handle rejection.
2218        assert_eq!(
2219            ui.compose(|group| {
2220                group.push_clip(RECT)?;
2221                assert_eq!(
2222                    group.compose(|inner| {
2223                        inner.modal(100)?;
2224                        inner.pop_clip()
2225                    }),
2226                    Err(UiError::InvalidLayout)
2227                );
2228                assert_eq!(group.ui.modal_blocker, Some(90));
2229                group.label(RECT, "READABLE FALLBACK", TextStyle::default())?;
2230                group.pop_clip()?;
2231                Ok(42)
2232            }),
2233            Ok(42)
2234        );
2235        assert_eq!(ui.state.captured(), Some(2));
2236        assert_eq!(ui.commands.len(), before.commands + 1);
2237        fn nest(group: &mut UiComposition<'_>, depth: usize) -> Result<(), UiError> {
2238            group.panel(RECT, PANEL)?;
2239            if depth == 16 {
2240                let mut called = false;
2241                assert_eq!(
2242                    group.compose(|_| {
2243                        called = true;
2244                        Ok(())
2245                    }),
2246                    Err(UiError::Capacity)
2247                );
2248                assert!(!called);
2249                Ok(())
2250            } else {
2251                group.compose(|inner| nest(inner, depth + 1))
2252            }
2253        }
2254        ui.compose(|group| nest(group, 1)).unwrap();
2255        assert_eq!(ui.commands.len(), before.commands + 17);
2256        // Propagation instead of local handling rejects every enclosing group.
2257        fn overflow(group: &mut UiComposition<'_>) -> Result<(), UiError> {
2258            group.panel(RECT, PANEL)?;
2259            group.compose(overflow)
2260        }
2261        let before = composition_snapshot(&ui);
2262        assert_eq!(ui.compose(overflow), Err(UiError::Capacity));
2263        assert_eq!(composition_snapshot(&ui), before);
2264        // A callback error is retained even if a newly pushed clip is open.
2265        assert_eq!(
2266            ui.compose(|group| {
2267                group.push_clip(RECT)?;
2268                Err::<(), _>(UiError::Capacity)
2269            }),
2270            Err(UiError::Capacity)
2271        );
2272        assert_eq!(composition_snapshot(&ui), before);
2273    }
2274    #[test]
2275    fn journey400_281_unwinding_and_release_preserve_prior_capture() {
2276        let mut ui = composition_prior();
2277        let before = composition_snapshot(&ui);
2278        let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2279            let _: Result<(), UiError> = ui.compose(|group| {
2280                composition_parts(group)?;
2281                panic!("injected callback panic")
2282            });
2283        }));
2284        assert!(panic.is_err());
2285        assert_eq!(composition_snapshot(&ui), before);
2286        // Actual host input is still delivered once, after rollback. The prior
2287        // owner can release/activate and rejected widgets never steal its tail.
2288        next();
2289        crate::button(1, false);
2290        ui.finish(true);
2291        assert!(ui.activated(2));
2292        assert_eq!(ui.interaction().pointer_activated, Some(2));
2293        assert_eq!(ui.interaction().pointer_capture, None);
2294        ui.state.end_frame();
2295        assert_eq!(ui.focused(), Some(2));
2296    }
2297    #[test]
2298    fn journey400_281_inactive_inspection_empty_groups_and_reset_preserve_defaults() {
2299        reset();
2300        let mut ui = Ui::new();
2301        let reserved = ui.reserved_bytes();
2302        begin(&mut ui);
2303        assert_eq!(ui.compose(|_| Ok(7)), Ok(7));
2304        assert!(ui.commands.is_empty());
2305        assert_eq!(ui.reserved_bytes(), reserved);
2306        button(&mut ui, 1, true);
2307        // Inspection configured after begin is intentionally inactive until the
2308        // next begin. Composition exposes no configuration/lifecycle methods.
2309        ui.set_inspection_enabled(true);
2310        let before = composition_snapshot(&ui);
2311        assert!(ui.inspect().is_none());
2312        assert_eq!(
2313            ui.compose(|group| {
2314                composition_parts(group)?;
2315                Err::<(), _>(UiError::Capacity)
2316            }),
2317            Err(UiError::Capacity)
2318        );
2319        assert_eq!(composition_snapshot(&ui), before);
2320        assert!(!ui.inspection.as_ref().unwrap().active);
2321        begin(&mut ui);
2322        assert!(ui.inspection.as_ref().unwrap().active);
2323        ui.compose(composition_parts).unwrap();
2324        assert_eq!(ui.inspect().unwrap().len(), 11); // Commands plus blocker.
2325        begin(&mut ui);
2326        assert_eq!(ui.inspect().unwrap().len(), 0);
2327        assert_eq!(ui.modal_blocker, None);
2328        assert_eq!(ui.clip_len, 1);
2329        assert_eq!(ui.vertices, 0);
2330        ui.compose(|group| group.button(106, RECT, "NEW", true, ButtonStyle::default()))
2331            .unwrap();
2332        assert_eq!(
2333            ui.inspect().unwrap().next().unwrap().label,
2334            UiLabel::Full("NEW")
2335        );
2336        ui.set_inspection_enabled(false);
2337        assert_eq!(ui.reserved_bytes(), reserved);
2338    }
2339    #[test]
2340    fn journey400_280_inspection_preserves_exact_paint_hit_and_input() {
2341        let run = |inspect: bool| {
2342            reset();
2343            crate::edit(|s| {
2344                s.w = 400;
2345                s.h = 240;
2346            });
2347            let mut ui = Ui::new();
2348            ui.set_inspection_enabled(inspect);
2349            let viewport = Viewport::fit([400., 240.], [100.; 2], [20., 10., 20., 30.]).unwrap();
2350            ui.begin(viewport);
2351            let clip = UiRect {
2352                min: [20., 30.],
2353                size: [10., 20.],
2354            };
2355            ui.push_clip(clip).unwrap();
2356            ui.hud_button(
2357                9,
2358                UiRect {
2359                    min: [10., 20.],
2360                    size: [80., 40.],
2361                },
2362                "RESUME EXPEDITION é",
2363                true,
2364                ButtonStyle::default(),
2365            )
2366            .unwrap();
2367            // Project a synthetic mouse press/release through this scaled safe area.
2368            let pixel: [f32; 2] = std::array::from_fn(|i| {
2369                viewport.pixels().min[i] + [25., 40.][i] * viewport.scale()
2370            });
2371            crate::pointer(pixel[0], pixel[1], 0., 0.);
2372            crate::button(1, true);
2373            crate::button(1, false);
2374            ui.finish(true);
2375            assert!(ui.activated(9));
2376            assert_eq!(ui.state.hit_test([25., 40.]), Some(9));
2377            for point in [[19.999, 40.], [30., 40.], [25., 50.]] {
2378                assert_eq!(ui.state.hit_test(point), None);
2379            }
2380            let before = (
2381                ui.state.focused(),
2382                ui.state.captured(),
2383                ui.interaction(),
2384                ui.active,
2385                ui.text.clone(),
2386                ui.commands.len(),
2387                ui.vertices,
2388                crate::read(|s| s.input.events().len()),
2389            );
2390            if inspect {
2391                for _ in 0..3 {
2392                    let element = ui.inspect().unwrap().next().unwrap();
2393                    assert_eq!(element.visible_bounds, Some(clip));
2394                    assert_eq!(element.label, UiLabel::Full("RESUME EXPEDITION é"));
2395                    assert!(element.enabled && element.focused && element.interaction_registered);
2396                    let mut bytes = [0; 2048];
2397                    ui.write_inspection(&mut bytes).unwrap();
2398                }
2399            }
2400            assert_eq!(
2401                before,
2402                (
2403                    ui.state.focused(),
2404                    ui.state.captured(),
2405                    ui.interaction(),
2406                    ui.active,
2407                    ui.text.clone(),
2408                    ui.commands.len(),
2409                    ui.vertices,
2410                    crate::read(|s| s.input.events().len())
2411                )
2412            );
2413            ui.paint();
2414            crate::read(|s| {
2415                // First six vertices are the actual button fill; compare all
2416                // corners to separately specified logical clipped geometry.
2417                let points = [
2418                    [20., 30.],
2419                    [30., 30.],
2420                    [30., 50.],
2421                    [20., 30.],
2422                    [30., 50.],
2423                    [20., 50.],
2424                ];
2425                for (vertex, point) in s.vertices[..6].iter().zip(points) {
2426                    let px = viewport.pixels().min[0] + point[0] * viewport.scale();
2427                    let py = viewport.pixels().min[1] + point[1] * viewport.scale();
2428                    assert_eq!(vertex[0], px / 400. * 2. - 1.);
2429                    assert_eq!(vertex[1], 1. - py / 240. * 2.);
2430                }
2431                (
2432                    s.vertices.clone(),
2433                    ui.interaction(),
2434                    ui.focused(),
2435                    ui.activated(9),
2436                )
2437            })
2438        };
2439        assert_eq!(run(false), run(true));
2440    }
2441
2442    #[test]
2443    fn journey400_280_opt_out_and_label_capacity_do_not_change_submission() {
2444        reset();
2445        let mut ui = Ui::new();
2446        begin(&mut ui);
2447        let capacities = (
2448            ui.commands.capacity(),
2449            ui.text.capacity(),
2450            ui.state.capacity(),
2451        );
2452        let default_reserved = ui.reserved_bytes();
2453        let huge = "é".repeat(50_000);
2454        ui.hud_button(1, RECT, &huge, true, ButtonStyle::default())
2455            .unwrap();
2456        assert!(ui.inspection.is_none());
2457        assert!(ui.inspect().is_none());
2458        assert_eq!(ui.text.len(), 5); // One 2-byte scalar followed by ellipsis.
2459        ui.set_inspection_enabled(true);
2460        assert!(
2461            ui.inspect().is_none(),
2462            "cannot reconstruct already shortened copy"
2463        );
2464        begin(&mut ui);
2465        let full = "é".repeat(16384); // Exactly 32 KiB, all scalar boundaries valid.
2466        ui.label(RECT, &full, TextStyle::default()).unwrap();
2467        ui.hud_button(
2468            2,
2469            RECT,
2470            "overflow after full arena",
2471            true,
2472            ButtonStyle::default(),
2473        )
2474        .unwrap();
2475        ui.hud_button(3, RECT, &huge, false, ButtonStyle::default())
2476            .unwrap();
2477        let elements: Vec<_> = ui.inspect().unwrap().collect();
2478        assert_eq!(elements[0].label, UiLabel::Full(&full));
2479        assert_eq!(
2480            elements[1].label,
2481            UiLabel::Unavailable { required_bytes: 25 }
2482        );
2483        assert_eq!(
2484            elements[2].label,
2485            UiLabel::Unavailable {
2486                required_bytes: huge.len()
2487            }
2488        );
2489        assert!(elements[1].painted_label.ends_with("..."));
2490        let storage = ui.inspection.as_ref().unwrap();
2491        assert_eq!((storage.text.len(), storage.labels.len()), (32768, 3));
2492        assert_eq!(
2493            (storage.text.capacity(), storage.labels.capacity()),
2494            (32768, 1024)
2495        );
2496        assert_eq!(
2497            capacities,
2498            (
2499                ui.commands.capacity(),
2500                ui.text.capacity(),
2501                ui.state.capacity()
2502            )
2503        );
2504        ui.set_inspection_enabled(false);
2505        assert!(ui.inspect().is_none());
2506        assert_eq!(ui.reserved_bytes(), default_reserved);
2507        assert_eq!(
2508            ui.commands.len(),
2509            3,
2510            "disabling preserves composed paint/input"
2511        );
2512    }
2513
2514    #[test]
2515    fn journey400_280_failed_commands_leave_no_inspection_or_stale_copy() {
2516        reset();
2517        let mut ui = Ui::new();
2518        ui.set_inspection_enabled(true);
2519        begin(&mut ui);
2520        ui.hud_button(
2521            1,
2522            RECT,
2523            "long original source",
2524            true,
2525            ButtonStyle::default(),
2526        )
2527        .unwrap();
2528        let before = (
2529            ui.commands.len(),
2530            ui.text.len(),
2531            ui.vertices,
2532            ui.inspection.as_ref().unwrap().labels.len(),
2533            ui.inspection.as_ref().unwrap().text.len(),
2534        );
2535        assert_eq!(
2536            ui.hud_button(
2537                1,
2538                RECT,
2539                "another original source",
2540                true,
2541                ButtonStyle::default()
2542            ),
2543            Err(UiError::DuplicateId)
2544        );
2545        assert_eq!(
2546            ui.label(
2547                RECT,
2548                "bad",
2549                TextStyle {
2550                    size: f32::NAN,
2551                    ..Default::default()
2552                }
2553            ),
2554            Err(UiError::InvalidLayout)
2555        );
2556        assert_eq!(
2557            before,
2558            (
2559                ui.commands.len(),
2560                ui.text.len(),
2561                ui.vertices,
2562                ui.inspection.as_ref().unwrap().labels.len(),
2563                ui.inspection.as_ref().unwrap().text.len()
2564            )
2565        );
2566        begin(&mut ui);
2567        assert_eq!(ui.inspect().unwrap().len(), 0);
2568        let all_text = "x".repeat(32768);
2569        ui.wrapped_text(RECT, &all_text, TextStyle::default(), LineLimit::Clip(0))
2570            .unwrap();
2571        assert_eq!(
2572            ui.label(RECT, "cannot append", TextStyle::default()),
2573            Err(UiError::Capacity)
2574        );
2575        assert_eq!(
2576            ui.button(2, RECT, "x", true, ButtonStyle::default()),
2577            Err(UiError::Capacity)
2578        );
2579        assert_eq!(ui.inspect().unwrap().len(), 1);
2580        assert_eq!(
2581            ui.inspect().unwrap().next().unwrap().label,
2582            UiLabel::Full(&all_text)
2583        );
2584        assert!(ui.inspection.as_ref().unwrap().labels.is_empty());
2585        begin(&mut ui);
2586        for _ in 0..1024 {
2587            ui.label(RECT, "", TextStyle::default()).unwrap();
2588        }
2589        assert_eq!(
2590            ui.label(RECT, "overflow", TextStyle::default()),
2591            Err(UiError::Capacity)
2592        );
2593        assert_eq!(ui.inspect().unwrap().count(), 1024);
2594        begin(&mut ui);
2595        ui.label(RECT, "fresh original source", TextStyle::default())
2596            .unwrap();
2597        assert_eq!(
2598            ui.inspect().unwrap().next().unwrap().label,
2599            UiLabel::Full("fresh original source")
2600        );
2601    }
2602
2603    #[test]
2604    fn journey400_280_modal_disabled_clipped_and_stale_ids_are_explicit() {
2605        reset();
2606        let mut ui = Ui::new();
2607        ui.set_inspection_enabled(true);
2608        begin(&mut ui);
2609        button(&mut ui, 1, true);
2610        ui.state.focus_next(false);
2611        ui.modal(90).unwrap();
2612        button(&mut ui, 2, true);
2613        ui.modal(91).unwrap();
2614        button(&mut ui, 1, false); // Reused ID in latest modal scope.
2615        ui.push_clip(UiRect {
2616            min: [180.; 2],
2617            size: [10.; 2],
2618        })
2619        .unwrap();
2620        button(&mut ui, 3, true);
2621        ui.pop_clip();
2622        ui.panel(RECT, INK).unwrap();
2623        ui.gradient(RECT, INK, PANEL).unwrap();
2624        ui.finish(true);
2625        let mut elements = ui.inspect().unwrap();
2626        assert_eq!(elements.len(), 7);
2627        let lower = elements.next().unwrap();
2628        assert_eq!(lower.id, Some(1));
2629        assert!(!lower.interaction_registered && !lower.focused);
2630        assert!(!elements.next().unwrap().interaction_registered);
2631        let blocker = elements.next().unwrap();
2632        assert_eq!(blocker.role, UiRole::ModalBlocker);
2633        assert_eq!(blocker.id, Some(91));
2634        assert!(blocker.interaction_registered && !blocker.focused);
2635        let disabled = elements.next().unwrap();
2636        assert!(!disabled.enabled && !disabled.focused);
2637        assert!(disabled.interaction_registered && disabled.visible_bounds.is_some());
2638        let clipped = elements.next().unwrap();
2639        assert!(clipped.enabled && clipped.interaction_registered && !clipped.focused);
2640        assert_eq!(clipped.visible_bounds, None);
2641        assert_eq!(elements.next().unwrap().role, UiRole::Panel);
2642        assert_eq!(elements.next().unwrap().role, UiRole::Gradient);
2643        assert_eq!(elements.len(), 0);
2644        assert_eq!(elements.next(), None);
2645        assert_eq!(elements.next(), None);
2646        next();
2647        begin(&mut ui);
2648        assert_eq!(ui.inspect().unwrap().next(), None);
2649        ui.modal(99).unwrap(); // Blocker at end, without any paint command.
2650        assert_eq!(ui.inspect().unwrap().len(), 1);
2651        assert_eq!(ui.inspect().unwrap().next().unwrap().id, Some(99));
2652        next();
2653        ui.begin(Viewport::responsive([0., 0.], [0.; 4]).unwrap());
2654        ui.button(5, RECT, "zero viewport", true, ButtonStyle::default())
2655            .unwrap();
2656        assert_eq!(ui.inspect().unwrap().next().unwrap().visible_bounds, None);
2657    }
2658
2659    #[test]
2660    fn journey400_279_ui_first_queue_survives_zero_ticks_without_stealing_movement() {
2661        use crate::input::{ActionKind, Binding, PlayerInput, host_frame};
2662        use ferravex_core::session::GameSession;
2663        reset();
2664        let mut ui = Ui::new();
2665        let mut player = PlayerInput::transient("ownership-ticks");
2666        for (name, code) in [("move", 100), ("jump", 32)] {
2667            player
2668                .action(
2669                    name,
2670                    name,
2671                    ActionKind::Button,
2672                    vec![Binding::digital(InputCode::Key(code))],
2673                )
2674                .unwrap();
2675        }
2676        // Enable the existing gameplay context before injecting host input.
2677        host_frame(0., 200, 200, || player.sample(true));
2678        let mut session = GameSession::try_new(64., 4, true).unwrap();
2679        let mut pending = None;
2680        let mut executed = Vec::new();
2681        let mut jumps = 0;
2682        crate::key(100, true);
2683        crate::key(32, true);
2684        crate::key(32, false);
2685        for (position, elapsed, expected_consumed, expected_ticks) in [
2686            ([40., 40.], 0., true, 0),
2687            ([150., 150.], 0., false, 0), // Queue full: reject this drop.
2688            ([150., 150.], 1. / 64., false, 1), // Execute the queued buy.
2689            ([150., 150.], 2. / 64., false, 2), // Execute one drop, two ticks.
2690        ] {
2691            crate::pointer(position[0], position[1], 0., 0.);
2692            crate::button(1, true);
2693            crate::button(1, false);
2694            host_frame(elapsed as f32, 200, 200, || {
2695                player.sample(true);
2696                begin(&mut ui);
2697                button(&mut ui, 1, true);
2698                ui.finish_player(&mut player, true);
2699                let ownership = ui.interaction();
2700                assert_eq!(ownership.pointer_consumed, expected_consumed);
2701                assert_eq!(ownership.pointer_activated, expected_consumed.then_some(1));
2702                assert_eq!(ownership.pointer_capture, None);
2703                assert!(!ownership.input_blocked);
2704                assert!(player.held("move"));
2705                assert_eq!(ui.interaction(), ownership, "inspection is read only");
2706                ui.finish_player(&mut player, true);
2707                assert_eq!(
2708                    ui.interaction(),
2709                    ownership,
2710                    "one journal delivery per frame"
2711                );
2712                let request = if ui.activated(1) {
2713                    Some("buy")
2714                } else if !ownership.pointer_consumed {
2715                    Some("drop")
2716                } else {
2717                    None
2718                };
2719                if pending.is_none() {
2720                    pending = request;
2721                }
2722                let frame = session.advance(elapsed);
2723                assert_eq!(frame.steps, expected_ticks);
2724                for _ in frame.ticks() {
2725                    let [movement, jump] = player.take_tick(["move", "jump"]);
2726                    assert_eq!(movement.value, 1.);
2727                    jumps += usize::from(jump.pressed);
2728                    if let Some(command) = pending.take() {
2729                        executed.push(command);
2730                    }
2731                }
2732                ui.paint();
2733            });
2734        }
2735        assert_eq!(executed, ["buy", "drop"]);
2736        assert_eq!(
2737            jumps, 1,
2738            "unrelated pending edge survives both zero-tick frames"
2739        );
2740        assert!(player.held("move"));
2741        assert_eq!(pending, None);
2742    }
2743
2744    #[test]
2745    fn journey400_279_capture_dragout_and_world_origin_follow_event_positions() {
2746        reset();
2747        let mut ui = Ui::new();
2748        begin(&mut ui);
2749        button(&mut ui, 1, true);
2750        crate::pointer(40., 40., 0., 0.);
2751        crate::button(1, true);
2752        ui.finish(true);
2753        assert!(ui.interaction().pointer_consumed);
2754        assert_eq!(ui.interaction().pointer_capture, Some(1));
2755        next();
2756        begin(&mut ui);
2757        button(&mut ui, 1, true);
2758        crate::pointer(150., 150., 110., 110.);
2759        ui.finish(true);
2760        assert!(
2761            ui.interaction().pointer_consumed,
2762            "held drag stays UI-owned"
2763        );
2764        next();
2765        begin(&mut ui);
2766        button(&mut ui, 1, true);
2767        crate::button(1, false);
2768        ui.finish(true);
2769        assert!(
2770            ui.interaction().pointer_consumed,
2771            "outside release stays UI-owned"
2772        );
2773        assert_eq!(ui.interaction().pointer_capture, None);
2774        assert_eq!(ui.interaction().pointer_activated, None);
2775        assert!(!ui.activated(1));
2776        next();
2777        begin(&mut ui);
2778        button(&mut ui, 1, true);
2779        crate::button(1, true); // World press.
2780        crate::pointer(40., 40., -110., -110.);
2781        crate::button(1, false);
2782        ui.finish(true);
2783        assert_eq!(ui.interaction(), UiInteraction::default());
2784        assert!(!ui.activated(1));
2785        next();
2786        begin(&mut ui);
2787        button(&mut ui, 1, true);
2788        // A UI tap followed by a world tap is deliberately conservative.
2789        crate::button(1, true);
2790        crate::button(1, false);
2791        crate::pointer(150., 150., 110., 110.);
2792        crate::button(1, true);
2793        crate::button(1, false);
2794        ui.finish(true);
2795        assert!(ui.interaction().pointer_consumed);
2796        assert_eq!(ui.interaction().pointer_activated, Some(1));
2797    }
2798
2799    #[test]
2800    fn journey400_279_disabled_occluded_clipped_and_paint_only_policy() {
2801        for (top_enabled, clipped, modal, paint_only, position, owner, active) in [
2802            (true, false, false, false, [40., 40.], Some(2), Some(2)),
2803            (false, false, false, false, [40., 40.], Some(2), None),
2804            (false, true, false, false, [40., 40.], Some(1), Some(1)),
2805            (true, false, true, false, [150., 150.], Some(99), Some(99)),
2806            (true, false, false, true, [150., 150.], None, None),
2807            (true, false, false, false, [200., 40.], None, None),
2808        ] {
2809            reset();
2810            let mut ui = Ui::new();
2811            begin(&mut ui);
2812            button(&mut ui, 1, true);
2813            if clipped {
2814                ui.push_clip(UiRect {
2815                    min: [120.; 2],
2816                    size: [20.; 2],
2817                })
2818                .unwrap();
2819            }
2820            button(&mut ui, 2, top_enabled);
2821            if clipped {
2822                ui.pop_clip();
2823            }
2824            if modal {
2825                ui.modal(99).unwrap();
2826            }
2827            if paint_only {
2828                ui.panel(ui.viewport.bounds(), PANEL).unwrap();
2829            }
2830            crate::pointer(position[0], position[1], 0., 0.);
2831            crate::button(1, true);
2832            ui.finish(true);
2833            assert_eq!(ui.interaction().pointer_capture, owner);
2834            next();
2835            // Keep the submitted frame geometry; next host frame releases it.
2836            crate::button(1, false);
2837            ui.finish(true);
2838            assert_eq!(ui.interaction().pointer_consumed, owner.is_some());
2839            assert_eq!(ui.interaction().pointer_activated, active);
2840            assert_eq!(ui.interaction().pointer_capture, None);
2841        }
2842    }
2843
2844    #[test]
2845    fn journey400_279_modal_close_cancel_disable_remove_and_release_tail() {
2846        // Exercise both primary pointer sources through the real journal.
2847        for touch in [false, true] {
2848            for mode in 0..7 {
2849                reset();
2850                let mut ui = Ui::new();
2851                begin(&mut ui);
2852                if mode == 4 {
2853                    ui.modal(1).unwrap();
2854                } else {
2855                    button(&mut ui, 1, true);
2856                }
2857                if touch {
2858                    crate::touch(7, 0, 40., 40.);
2859                } else {
2860                    crate::pointer(40., 40., 0., 0.);
2861                    crate::button(1, true);
2862                }
2863                ui.finish(true);
2864                assert_eq!(ui.interaction().pointer_capture, Some(1));
2865                next();
2866                begin(&mut ui);
2867                if !matches!(mode, 2 | 4) {
2868                    button(&mut ui, 1, mode != 3);
2869                }
2870                if mode == 0 {
2871                    ui.cancel();
2872                }
2873                if mode == 5 {
2874                    crate::edit(|s| s.controls_open = true);
2875                }
2876                if mode == 6 {
2877                    crate::key(0xff1b, true);
2878                }
2879                ui.finish(mode != 1);
2880                assert!(ui.interaction().pointer_consumed);
2881                assert_eq!(ui.interaction().pointer_capture, Some(1));
2882                assert_eq!(ui.interaction().input_blocked, mode == 5);
2883                next();
2884                begin(&mut ui);
2885                // Close the modal/editor or re-enable UI before the release.
2886                crate::edit(|s| s.controls_open = false);
2887                if touch {
2888                    crate::touch(7, 2, 40., 40.);
2889                } else {
2890                    crate::button(1, false);
2891                }
2892                ui.finish(true);
2893                assert!(
2894                    ui.interaction().pointer_consumed,
2895                    "touch={touch}, mode={mode}"
2896                );
2897                assert_eq!(ui.interaction().pointer_capture, None);
2898                assert_eq!(ui.interaction().pointer_activated, None);
2899                next();
2900                begin(&mut ui);
2901                ui.finish(true);
2902                assert_eq!(ui.interaction(), UiInteraction::default());
2903            }
2904        }
2905    }
2906
2907    #[test]
2908    fn journey400_279_touch_cancel_and_other_touch_do_not_release_owner() {
2909        reset();
2910        let mut ui = Ui::new();
2911        begin(&mut ui);
2912        button(&mut ui, 1, true);
2913        crate::touch(7, 0, 40., 40.);
2914        crate::touch(8, 0, 40., 40.);
2915        crate::touch(8, 2, 40., 40.);
2916        ui.finish(true);
2917        assert_eq!(ui.interaction().pointer_capture, Some(1));
2918        next();
2919        begin(&mut ui);
2920        button(&mut ui, 1, true);
2921        crate::touch(7, 3, 40., 40.);
2922        ui.finish(true);
2923        assert!(ui.interaction().pointer_consumed);
2924        assert_eq!(ui.interaction().pointer_capture, None);
2925        assert_eq!(ui.interaction().pointer_activated, None);
2926        next();
2927        begin(&mut ui);
2928        button(&mut ui, 1, true);
2929        crate::touch(9, 0, 150., 150.);
2930        crate::touch(9, 2, 40., 40.);
2931        ui.finish(true);
2932        assert_eq!(ui.interaction(), UiInteraction::default());
2933    }
2934
2935    #[test]
2936    fn journey400_279_cancelled_tail_cannot_be_stolen_by_a_second_pointer() {
2937        for mouse in [false, true] {
2938            reset();
2939            let mut ui = Ui::new();
2940            begin(&mut ui);
2941            button(&mut ui, 1, true);
2942            crate::touch(7, 0, 40., 40.);
2943            ui.finish(true);
2944            ui.cancel();
2945            next();
2946            begin(&mut ui);
2947            button(&mut ui, 1, true);
2948            if mouse {
2949                crate::pointer(40., 40., 0., 0.);
2950                crate::button(1, true);
2951            } else {
2952                crate::touch(8, 0, 40., 40.);
2953            }
2954            crate::touch(7, 2, 40., 40.);
2955            ui.finish(true);
2956            assert!(ui.interaction().pointer_consumed);
2957            assert_eq!(ui.interaction().pointer_capture, None);
2958            assert_eq!(ui.interaction().pointer_activated, None);
2959            next();
2960            begin(&mut ui);
2961            button(&mut ui, 1, true);
2962            if mouse {
2963                crate::button(1, false);
2964            } else {
2965                crate::touch(8, 2, 40., 40.);
2966            }
2967            ui.finish(true);
2968            assert_eq!(ui.interaction(), UiInteraction::default());
2969            assert!(!ui.activated(1));
2970        }
2971    }
2972
2973    #[test]
2974    fn journey400_279_confirm_sources_are_explicit_and_unrelated_edges_remain() {
2975        use crate::input::{ActionKind, Binding, PlayerInput};
2976        reset();
2977        let mut player = PlayerInput::transient("ownership-confirm");
2978        player
2979            .global_action(
2980                "confirm",
2981                "Confirm",
2982                ActionKind::Button,
2983                vec![Binding::digital(InputCode::Key(106))],
2984            )
2985            .unwrap();
2986        player
2987            .action(
2988                "jump",
2989                "Jump",
2990                ActionKind::Button,
2991                vec![Binding::digital(InputCode::Key(32))],
2992            )
2993            .unwrap();
2994        let mut ui = Ui::new();
2995        ui.set_auto_focus(false);
2996        player.sample(true);
2997        next();
2998        begin(&mut ui);
2999        button(&mut ui, 1, true);
3000        crate::key(106, true);
3001        crate::key(106, false);
3002        player.sample(true);
3003        ui.finish_player(&mut player, true);
3004        assert_eq!(
3005            ui.interaction(),
3006            UiInteraction::default(),
3007            "no focus, no acceptance"
3008        );
3009        next();
3010        begin(&mut ui);
3011        button(&mut ui, 1, true);
3012        crate::key(0xff09, true);
3013        crate::key(0xff09, false);
3014        crate::key(106, true);
3015        crate::key(106, false);
3016        crate::key(32, true);
3017        crate::key(32, false);
3018        player.sample(true);
3019        ui.finish_player(&mut player, true);
3020        assert_eq!(ui.interaction().player_confirmed, Some(1));
3021        assert_eq!(ui.interaction().keyboard_confirmed, None);
3022        assert_eq!(ui.interaction().pointer_activated, None);
3023        assert!(!ui.interaction().pointer_consumed);
3024        assert!(
3025            !player.pressed("confirm"),
3026            "legacy global-confirm consumption"
3027        );
3028        assert!(player.take_tick(["jump"])[0].pressed);
3029        let result = ui.interaction();
3030        begin(&mut ui); // A second layout/finish must not replay the journal.
3031        button(&mut ui, 1, true);
3032        ui.finish_player(&mut player, true);
3033        assert_eq!(ui.interaction(), result);
3034        next();
3035        begin(&mut ui);
3036        button(&mut ui, 1, true);
3037        crate::key(0xff0d, true);
3038        crate::key(0xff0d, false);
3039        ui.finish(true);
3040        assert_eq!(ui.interaction().keyboard_confirmed, Some(1));
3041        assert_eq!(ui.interaction().player_confirmed, None);
3042        next();
3043        crate::edit(|s| s.input.pad_connected(1, true));
3044        begin(&mut ui);
3045        button(&mut ui, 1, true);
3046        ui.finish_with_gamepad(true, 1); // First sample establishes pad epoch.
3047        next();
3048        begin(&mut ui);
3049        button(&mut ui, 1, true);
3050        crate::edit(|s| s.input.pad_button(1, 0, 1.));
3051        ui.finish_with_gamepad(true, 1);
3052        assert_eq!(ui.interaction().gamepad_confirmed, Some(1));
3053        assert_eq!(ui.interaction().keyboard_confirmed, None);
3054        assert_eq!(ui.interaction().pointer_capture, None);
3055    }
3056
3057    #[test]
3058    fn journey400_279_focus_overflow_and_blocked_ui_fail_closed_then_reset() {
3059        for overflow in [false, true] {
3060            reset();
3061            let mut ui = Ui::new();
3062            begin(&mut ui);
3063            button(&mut ui, 1, true);
3064            crate::pointer(40., 40., 0., 0.);
3065            crate::button(1, true);
3066            ui.finish(true);
3067            next();
3068            begin(&mut ui);
3069            button(&mut ui, 1, true);
3070            crate::edit(|s| {
3071                if overflow {
3072                    for _ in 0..=crate::input::MAX_EVENTS {
3073                        s.input
3074                            .push(PlatformEvent::PointerPosition(crate::Vec2::ZERO));
3075                    }
3076                    assert!(s.input.overflow);
3077                } else {
3078                    s.input.focus(false);
3079                }
3080            });
3081            ui.finish(true);
3082            assert!(ui.interaction().input_blocked);
3083            assert!(ui.interaction().pointer_consumed);
3084            assert_eq!(ui.interaction().pointer_capture, None);
3085            assert_eq!(ui.interaction().pointer_activated, None);
3086            next();
3087            begin(&mut ui);
3088            button(&mut ui, 1, true);
3089            crate::edit(|s| s.input.focus(true));
3090            crate::button(1, false);
3091            ui.finish(true);
3092            assert_eq!(ui.interaction(), UiInteraction::default());
3093            assert!(!ui.activated(1));
3094        }
3095        reset();
3096        let mut ui = Ui::new();
3097        begin(&mut ui);
3098        button(&mut ui, 1, true);
3099        crate::pointer(40., 40., 0., 0.);
3100        crate::button(1, true);
3101        crate::button(1, false);
3102        ui.finish(false);
3103        assert_eq!(
3104            ui.interaction(),
3105            UiInteraction::default(),
3106            "UI disabled, world allowed"
3107        );
3108        next();
3109        begin(&mut ui);
3110        crate::edit(|s| s.controls_open = true);
3111        ui.finish(true);
3112        assert!(ui.interaction().input_blocked);
3113        crate::edit(|s| s.controls_open = false);
3114        ui.finish(true);
3115        assert!(
3116            ui.interaction().input_blocked,
3117            "same-frame close cannot leak earlier input"
3118        );
3119        next();
3120        begin(&mut ui);
3121        ui.finish(true);
3122        assert_eq!(ui.interaction(), UiInteraction::default());
3123    }
3124
3125    #[test]
3126    fn journey400_279_ownership_uses_the_same_scaled_safe_area_clip_as_widgets() {
3127        reset();
3128        let mut ui = Ui::new();
3129        let viewport = Viewport::fit([400., 240.], [200.; 2], [12., 8., 12., 8.]).unwrap();
3130        ui.begin(viewport);
3131        ui.push_clip(UiRect {
3132            min: [30.; 2],
3133            size: [20.; 2],
3134        })
3135        .unwrap();
3136        button(&mut ui, 1, true);
3137        ui.pop_clip();
3138        // [40, 40] is visible, [25, 40] lies inside the button but outside its clip.
3139        for (logical, expected) in [([40., 40.], Some(1)), ([25., 40.], None)] {
3140            let pixels: [f32; 2] = std::array::from_fn(|axis| {
3141                viewport.pixels().min[axis] + logical[axis] * viewport.scale()
3142            });
3143            crate::pointer(pixels[0], pixels[1], 0., 0.);
3144            crate::button(1, true);
3145            crate::button(1, false);
3146            ui.finish(true);
3147            assert_eq!(ui.interaction().pointer_activated, expected);
3148            assert_eq!(ui.interaction().pointer_consumed, expected.is_some());
3149            next();
3150        }
3151    }
3152
3153    #[test]
3154    fn journey400_279_rejected_widgets_never_claim_and_full_frame_stays_bounded() {
3155        reset();
3156        let mut ui = Ui::new();
3157        let reserved = ui.reserved_bytes();
3158        begin(&mut ui);
3159        for id in 0..1024 {
3160            ui.button(id, RECT, "", true, ButtonStyle::default())
3161                .unwrap();
3162        }
3163        let rejected = UiRect {
3164            min: [140.; 2],
3165            size: [40.; 2],
3166        };
3167        assert_eq!(
3168            ui.button(1024, rejected, "", true, ButtonStyle::default()),
3169            Err(UiError::Capacity)
3170        );
3171        crate::pointer(150., 150., 0., 0.);
3172        crate::button(1, true);
3173        crate::button(1, false);
3174        ui.finish(true);
3175        assert_eq!(ui.interaction(), UiInteraction::default());
3176        next();
3177        crate::pointer(40., 40., 0., 0.);
3178        crate::button(1, true);
3179        crate::button(1, false);
3180        ui.finish(true);
3181        assert_eq!(ui.interaction().pointer_activated, Some(1023));
3182        next();
3183        begin(&mut ui);
3184        button(&mut ui, 1, true);
3185        assert_eq!(
3186            ui.button(1, rejected, "", true, ButtonStyle::default()),
3187            Err(UiError::DuplicateId)
3188        );
3189        assert_eq!(
3190            ui.button(
3191                2,
3192                rejected,
3193                "",
3194                true,
3195                ButtonStyle {
3196                    size: f32::NAN,
3197                    ..Default::default()
3198                }
3199            ),
3200            Err(UiError::InvalidLayout)
3201        );
3202        crate::pointer(150., 150., 0., 0.);
3203        crate::button(1, true);
3204        crate::button(1, false);
3205        ui.finish(true);
3206        assert_eq!(ui.interaction(), UiInteraction::default());
3207        assert_eq!(ui.reserved_bytes(), reserved);
3208    }
3209    #[test]
3210    fn ordered_taps_release_outside_multitouch_and_focus_loss() {
3211        reset();
3212        let mut ui = Ui::new();
3213        begin(&mut ui);
3214        button(&mut ui, 1, true);
3215        crate::touch(7, 0, 40., 40.);
3216        crate::touch(8, 0, 40., 40.);
3217        crate::touch(8, 2, 40., 40.);
3218        ui.finish(true);
3219        assert!(!ui.activated(1));
3220        next();
3221        begin(&mut ui);
3222        button(&mut ui, 1, true);
3223        crate::touch(7, 2, 150., 150.);
3224        ui.finish(true);
3225        assert!(!ui.activated(1));
3226        next();
3227        begin(&mut ui);
3228        button(&mut ui, 1, true);
3229        crate::touch(9, 0, 40., 40.);
3230        crate::touch(9, 2, 40., 40.);
3231        ui.finish(true);
3232        assert!(ui.activated(1));
3233        next();
3234        begin(&mut ui);
3235        button(&mut ui, 1, true);
3236        crate::touch(10, 0, 40., 40.);
3237        ui.finish(true);
3238        next();
3239        begin(&mut ui);
3240        button(&mut ui, 1, true);
3241        crate::edit(|s| s.input.focus(false));
3242        ui.finish(true);
3243        next();
3244        begin(&mut ui);
3245        button(&mut ui, 1, true);
3246        crate::edit(|s| s.input.focus(true));
3247        crate::touch(10, 2, 40., 40.);
3248        ui.finish(true);
3249        assert!(!ui.activated(1));
3250    }
3251    #[test]
3252    fn event_time_mouse_positions_and_pointer_ownership_prevent_false_clicks() {
3253        reset();
3254        let mut ui = Ui::new();
3255        begin(&mut ui);
3256        button(&mut ui, 1, true);
3257        crate::pointer(150., 150., 0., 0.);
3258        crate::button(1, true);
3259        crate::pointer(40., 40., -110., -110.);
3260        crate::button(1, false);
3261        ui.finish(true);
3262        assert!(
3263            !ui.activated(1),
3264            "outside press then inside release in one frame"
3265        );
3266        next();
3267        begin(&mut ui);
3268        button(&mut ui, 1, true);
3269        crate::pointer(40., 40., 0., 0.);
3270        crate::button(1, true);
3271        crate::touch(7, 0, 40., 40.);
3272        crate::touch(7, 2, 40., 40.);
3273        ui.finish(true);
3274        assert!(!ui.activated(1), "touch cannot steal mouse capture");
3275        next();
3276        begin(&mut ui);
3277        button(&mut ui, 1, true);
3278        crate::button(1, false);
3279        ui.finish(true);
3280        assert!(ui.activated(1));
3281    }
3282    #[test]
3283    fn keyboard_pad_modal_and_disabled_focus() {
3284        reset();
3285        let mut ui = Ui::new();
3286        begin(&mut ui);
3287        button(&mut ui, 1, false);
3288        button(&mut ui, 2, true);
3289        crate::key(0xff09, true);
3290        crate::key(0xff09, false);
3291        crate::key(0xff0d, true);
3292        crate::key(0xff0d, false);
3293        ui.finish(true);
3294        assert!(ui.activated(2));
3295        next();
3296        crate::edit(|s| s.input.pad_connected(1, true));
3297        begin(&mut ui);
3298        ui.finish_with_gamepad(false, 1);
3299        next();
3300        begin(&mut ui);
3301        button(&mut ui, 2, true);
3302        ui.modal(100).unwrap();
3303        button(&mut ui, 3, true);
3304        crate::edit(|s| {
3305            s.input.pad_connected(1, true);
3306            s.input.pad_button(1, 0, 1.);
3307        });
3308        ui.finish_with_gamepad(true, 1);
3309        assert_eq!(ui.focused(), Some(3));
3310        assert!(ui.activated(3));
3311        next();
3312        begin(&mut ui);
3313        button(&mut ui, 3, false);
3314        crate::touch(1, 0, 40., 40.);
3315        crate::touch(1, 2, 40., 40.);
3316        ui.finish(true);
3317        assert!(!ui.activated(3));
3318        assert_eq!(ui.focused(), None);
3319        next();
3320        begin(&mut ui);
3321        button(&mut ui, 3, true);
3322        crate::touch(2, 0, 40., 40.);
3323        crate::touch(2, 2, 40., 40.);
3324        crate::edit(|s| s.controls_open = true);
3325        ui.finish(true);
3326        assert!(!ui.activated(3));
3327    }
3328    #[test]
3329    fn remapped_confirm_and_explicit_focus_preserve_gameplay_roles() {
3330        use crate::input::{ActionKind, Binding, InputCode, PlayerInput};
3331        reset();
3332        let mut player = PlayerInput::transient("ui-test");
3333        player
3334            .global_action(
3335                "confirm",
3336                "Confirm",
3337                ActionKind::Button,
3338                vec![Binding::digital(InputCode::Key(106))],
3339            )
3340            .unwrap();
3341        let mut ui = Ui::new();
3342        ui.set_auto_focus(false);
3343        begin(&mut ui);
3344        button(&mut ui, 1, true);
3345        crate::key(106, true);
3346        crate::key(106, false);
3347        player.sample(true);
3348        ui.finish_player(&mut player, true);
3349        assert!(!ui.activated(1));
3350        next();
3351        begin(&mut ui);
3352        button(&mut ui, 1, true);
3353        crate::key(0xff09, true);
3354        crate::key(0xff09, false);
3355        crate::key(106, true);
3356        crate::key(106, false);
3357        player.sample(true);
3358        ui.finish_player(&mut player, true);
3359        assert!(ui.activated(1));
3360        next();
3361        begin(&mut ui);
3362        button(&mut ui, 1, true);
3363        crate::key(106, true);
3364        crate::key(106, false);
3365        player.sample(true);
3366        ui.finish_player(&mut player, false);
3367        assert!(!ui.activated(1));
3368    }
3369    #[test]
3370    fn clipped_screen_geometry_keeps_camera_and_world_order() {
3371        reset();
3372        crate::edit(|s| {
3373            s.w = 400;
3374            s.h = 200;
3375        });
3376        let matrix = crate::Mat4::from_scale(crate::Vec3::splat(7.));
3377        crate::edit(|s| {
3378            s.matrix = matrix;
3379            s.depth = true;
3380        });
3381        let mut ui = Ui::new();
3382        ui.begin(Viewport::fit([400., 200.], [100.; 2], [0.; 4]).unwrap());
3383        ui.push_clip(UiRect {
3384            min: [20., 30.],
3385            size: [10., 20.],
3386        })
3387        .unwrap();
3388        ui.panel(
3389            UiRect {
3390                min: [0.; 2],
3391                size: [100.; 2],
3392            },
3393            INK,
3394        )
3395        .unwrap();
3396        ui.text(
3397            RECT,
3398            "?é\nAB",
3399            TextStyle {
3400                wrap: true,
3401                shadow: true,
3402                ..Default::default()
3403            },
3404        )
3405        .unwrap();
3406        ui.finish(false);
3407        ui.paint();
3408        crate::read(|s| {
3409            assert_eq!(s.matrix, matrix);
3410            assert!(s.depth);
3411            assert!(!s.batches[0].depth);
3412            assert!(
3413                s.vertices
3414                    .iter()
3415                    .all(|v| (-0.301..=-0.199).contains(&v[0]) && (-0.001..=0.401).contains(&v[1]))
3416            );
3417            assert!(s.vertices.len() >= 6);
3418            assert!(s.vertices.len() <= ui.vertices);
3419        });
3420    }
3421    #[test]
3422    fn clipped_gradient_interpolates_original_colors() {
3423        reset();
3424        crate::edit(|s| {
3425            s.w = 200;
3426            s.h = 200;
3427        });
3428        let mut ui = Ui::new();
3429        begin(&mut ui);
3430        ui.push_clip(UiRect {
3431            min: [50., 0.],
3432            size: [100., 200.],
3433        })
3434        .unwrap();
3435        ui.gradient(
3436            UiRect {
3437                min: [0.; 2],
3438                size: [200.; 2],
3439            },
3440            Color::new(1., 0., 0., 1.),
3441            Color::new(0., 0., 1., 0.),
3442        )
3443        .unwrap();
3444        ui.paint();
3445        crate::read(|s| {
3446            assert_eq!(s.vertices.len(), 6);
3447            assert_eq!(&s.vertices[0][4..], &[0.75, 0., 0.25, 0.75]);
3448            assert_eq!(&s.vertices[1][4..], &[0.25, 0., 0.75, 0.25]);
3449        });
3450    }
3451    #[test]
3452    fn wrapped_help_keeps_words_and_explicit_blank_lines_readable() {
3453        assert_eq!(
3454            Lines::new("Five amber gates then land", 12).collect::<Vec<_>>(),
3455            ["Five amber", "gates then", "land"]
3456        );
3457        assert_eq!(
3458            Lines::new("alpha  beta\n\né日A", 5).collect::<Vec<_>>(),
3459            ["alpha", "beta", "", "é日A"]
3460        );
3461        assert_eq!(
3462            Lines::new("é日ABC", 2).collect::<Vec<_>>(),
3463            ["é日", "AB", "C"]
3464        );
3465        assert_eq!(Lines::new("AB", 0).collect::<Vec<_>>(), ["A", "B"]);
3466    }
3467
3468    fn painted_lines(
3469        lines: &[&str],
3470        rect: UiRect,
3471        clip: UiRect,
3472        style: TextStyle,
3473    ) -> Vec<[f32; 8]> {
3474        let mut vertices = Vec::new();
3475        let mut painter = Painter {
3476            vertices: &mut vertices,
3477            viewport: Viewport::responsive([320., 240.], [0.; 4]).unwrap(),
3478            screen: [320., 240.],
3479        };
3480        for (index, line) in lines.iter().enumerate() {
3481            let offset = index as f32 * style.size;
3482            if offset >= rect.size[1] {
3483                break;
3484            }
3485            painter.text(
3486                UiRect {
3487                    min: [rect.min[0], rect.min[1] + offset],
3488                    size: [rect.size[0], rect.size[1] - offset],
3489                },
3490                clip,
3491                line,
3492                style,
3493                LineLimit::Unlimited,
3494            );
3495        }
3496        vertices
3497    }
3498
3499    #[test]
3500    fn journey400_273_measure_legacy_and_queued_paint_share_line_geometry() {
3501        reset();
3502        crate::edit(|s| {
3503            s.w = 320;
3504            s.h = 240;
3505        });
3506        for (copy, columns, expected) in [
3507            (
3508                "Five amber gates then land",
3509                12,
3510                vec!["Five amber", "gates then", "land"],
3511            ),
3512            ("alpha  beta\n\né日A", 5, vec!["alpha", "beta", "", "??A"]),
3513            ("é日ABC", 2, vec!["??", "AB", "C"]),
3514            ("A\r\nB", 5, vec!["A?", "B"]),
3515            ("A\t\r B", 2, vec!["A", "B"]),
3516            ("\nA\n\n", 2, vec!["", "A", ""]),
3517        ] {
3518            for size in [8., 18.5] {
3519                for align in [Align::Left, Align::Center, Align::Right] {
3520                    for height in [0., size * 1.5, 180.] {
3521                        next();
3522                        let rect = UiRect {
3523                            min: [16., 24.],
3524                            size: [columns as f32 * (size / 8. * 6.), height],
3525                        };
3526                        let clip = UiRect {
3527                            min: [18., 25.],
3528                            size: [280., 170.],
3529                        };
3530                        let style = TextStyle {
3531                            size,
3532                            align,
3533                            wrap: true,
3534                            shadow: true,
3535                            ..Default::default()
3536                        };
3537                        let oracle = painted_lines(&expected, rect, clip, style);
3538                        let mut legacy = Vec::new();
3539                        Painter {
3540                            vertices: &mut legacy,
3541                            viewport: Viewport::responsive([320., 240.], [0.; 4]).unwrap(),
3542                            screen: [320., 240.],
3543                        }
3544                        .text(
3545                            rect,
3546                            clip,
3547                            copy,
3548                            style,
3549                            LineLimit::Unlimited,
3550                        );
3551                        assert_eq!(legacy, oracle, "legacy: {copy:?} {size} {height}");
3552                        let mut ui = Ui::new();
3553                        ui.begin(Viewport::responsive([320., 240.], [0.; 4]).unwrap());
3554                        ui.push_clip(clip).unwrap();
3555                        let report = ui
3556                            .wrapped_text(rect, copy, style, LineLimit::Unlimited)
3557                            .unwrap();
3558                        assert_eq!(report.line_count, expected.len());
3559                        assert_eq!(report.required_height, expected.len() as f32 * size);
3560                        // Geometric clipping does not pretend to be a line policy.
3561                        assert_eq!(report.hidden_lines, 0);
3562                        ui.paint();
3563                        crate::read(|s| {
3564                            assert_eq!(s.vertices, oracle, "queued: {copy:?} {size} {height}");
3565                            assert!(s.vertices.len() <= ui.vertices);
3566                            for vertex in &s.vertices {
3567                                let p = [(vertex[0] + 1.) * 160., (1. - vertex[1]) * 120.];
3568                                let visible = rect.intersect(clip).unwrap();
3569                                for (axis, coordinate) in p.into_iter().enumerate() {
3570                                    assert!(coordinate >= visible.min[axis] - 0.001);
3571                                    assert!(
3572                                        coordinate
3573                                            <= visible.min[axis] + visible.size[axis] + 0.001
3574                                    );
3575                                }
3576                            }
3577                        });
3578                    }
3579                }
3580            }
3581        }
3582    }
3583
3584    #[test]
3585    fn journey400_273_final_line_marker_and_partial_height_clipping_are_explicit() {
3586        reset();
3587        crate::edit(|s| {
3588            s.w = 320;
3589            s.h = 240;
3590        });
3591        let viewport = Viewport::responsive([320., 240.], [0.; 4]).unwrap();
3592        let style = TextStyle {
3593            size: 8.,
3594            align: Align::Right,
3595            shadow: true,
3596            ..Default::default()
3597        };
3598        for (limit, expected) in [
3599            (LineLimit::Unlimited, vec!["??ABC", "DEF", "G"]),
3600            (LineLimit::Clip(1), vec!["??ABC"]),
3601            (LineLimit::Ellipsis(1), vec!["??..."]),
3602            (LineLimit::Ellipsis(2), vec!["??ABC", "DE..."]),
3603            (LineLimit::Ellipsis(3), vec!["??ABC", "DEF", "G"]),
3604            (LineLimit::Ellipsis(0), vec![]),
3605        ] {
3606            for height in [0., 4., 8., 12., 24.] {
3607                next();
3608                let rect = UiRect {
3609                    min: [16., 24.],
3610                    size: [30., height],
3611                };
3612                let mut ui = Ui::new();
3613                ui.begin(viewport);
3614                let report = ui
3615                    .wrapped_text(rect, "é日ABC DEF\nG", style, limit)
3616                    .unwrap();
3617                assert_eq!(report.visible_lines, expected.len());
3618                assert_eq!(report.hidden_lines, 3 - expected.len());
3619                assert_eq!(report.required_height, 24.);
3620                ui.paint();
3621                let oracle = painted_lines(
3622                    &expected,
3623                    rect,
3624                    rect,
3625                    TextStyle {
3626                        wrap: true,
3627                        ..style
3628                    },
3629                );
3630                crate::read(|s| {
3631                    assert_eq!(s.vertices, oracle);
3632                    assert!(s.vertices.len() <= ui.vertices);
3633                });
3634            }
3635        }
3636        // Legacy non-wrapped copy still shrinks all lines to fit the longest.
3637        let rect = UiRect {
3638            min: [16., 24.],
3639            size: [12., 16.],
3640        };
3641        let mut actual = Vec::new();
3642        Painter {
3643            vertices: &mut actual,
3644            viewport,
3645            screen: [320., 240.],
3646        }
3647        .text(rect, rect, "ABCD\nEF", style, LineLimit::Unlimited);
3648        assert_eq!(
3649            actual,
3650            painted_lines(
3651                &["ABCD", "EF"],
3652                rect,
3653                rect,
3654                TextStyle {
3655                    size: 4.,
3656                    wrap: true,
3657                    ..style
3658                }
3659            )
3660        );
3661    }
3662
3663    #[test]
3664    fn journey400_273_rejections_are_atomic_and_begin_restores_budgets() {
3665        reset();
3666        let mut ui = Ui::new();
3667        begin(&mut ui);
3668        ui.text(RECT, "kept", TextStyle::default()).unwrap();
3669        let before = (ui.commands.len(), ui.text.clone(), ui.vertices);
3670        let huge = "A".repeat(32769);
3671        for (rect, copy, style, limit, error) in [
3672            (
3673                RECT,
3674                "bad",
3675                TextStyle {
3676                    size: f32::NAN,
3677                    ..Default::default()
3678                },
3679                LineLimit::Unlimited,
3680                UiError::InvalidLayout,
3681            ),
3682            (
3683                RECT,
3684                "bad",
3685                TextStyle {
3686                    color: Color::new(f32::NAN, 0., 0., 1.),
3687                    ..Default::default()
3688                },
3689                LineLimit::Unlimited,
3690                UiError::InvalidLayout,
3691            ),
3692            (
3693                UiRect {
3694                    min: [f32::INFINITY, 0.],
3695                    ..RECT
3696                },
3697                "bad",
3698                TextStyle::default(),
3699                LineLimit::Clip(0),
3700                UiError::InvalidLayout,
3701            ),
3702            (
3703                RECT,
3704                huge.as_str(),
3705                TextStyle::default(),
3706                LineLimit::Clip(0),
3707                UiError::Capacity,
3708            ),
3709            (
3710                RECT,
3711                &huge[..2000],
3712                TextStyle::default(),
3713                LineLimit::Unlimited,
3714                UiError::Capacity,
3715            ),
3716        ] {
3717            assert_eq!(ui.wrapped_text(rect, copy, style, limit), Err(error));
3718            assert_eq!((ui.commands.len(), ui.text.clone(), ui.vertices), before);
3719        }
3720        let storage = (ui.commands.as_ptr(), ui.text.as_ptr(), ui.reserved_bytes());
3721        begin(&mut ui);
3722        // Full arena accepted for an explicit zero-line policy; no glyph budget.
3723        let report = ui
3724            .wrapped_text(
3725                RECT,
3726                &huge[..32768],
3727                TextStyle::default(),
3728                LineLimit::Clip(0),
3729            )
3730            .unwrap();
3731        assert!(report.is_truncated());
3732        assert_eq!(ui.vertices, 0);
3733        assert_eq!(ui.text.len(), 32768);
3734        assert_eq!(
3735            ui.wrapped_text(RECT, "A", TextStyle::default(), LineLimit::Clip(0)),
3736            Err(UiError::Capacity)
3737        );
3738        assert_eq!(ui.text.len(), 32768);
3739        begin(&mut ui);
3740        for _ in 0..1024 {
3741            ui.wrapped_text(RECT, "", TextStyle::default(), LineLimit::Unlimited)
3742                .unwrap();
3743        }
3744        assert_eq!(
3745            ui.wrapped_text(RECT, "", TextStyle::default(), LineLimit::Unlimited),
3746            Err(UiError::Capacity)
3747        );
3748        assert_eq!(ui.commands.len(), 1024);
3749        begin(&mut ui);
3750        assert!(ui.commands.is_empty() && ui.text.is_empty());
3751        let report = ui
3752            .wrapped_text(RECT, "NEW", TextStyle::default(), LineLimit::Unlimited)
3753            .unwrap();
3754        assert_eq!((report.line_count, report.hidden_lines), (1, 0));
3755        assert_eq!(
3756            (ui.commands.as_ptr(), ui.text.as_ptr(), ui.reserved_bytes()),
3757            storage
3758        );
3759    }
3760
3761    #[test]
3762    fn bounded_commands_text_rollback_and_utf8_wrapping() {
3763        reset();
3764        let mut ui = Ui::new();
3765        begin(&mut ui);
3766        let huge = "é".repeat(17000);
3767        assert_eq!(
3768            ui.text(RECT, &huge, TextStyle::default()),
3769            Err(UiError::Capacity)
3770        );
3771        assert!(ui.text.is_empty());
3772        assert!(ui.commands.is_empty());
3773        assert_eq!(
3774            Lines::new("é日A\nB", 2).collect::<Vec<_>>(),
3775            vec!["é日", "A", "B"]
3776        );
3777        for _ in 1..16 {
3778            ui.push_clip(RECT).unwrap();
3779        }
3780        assert_eq!(ui.push_clip(RECT), Err(UiError::Capacity));
3781        for _ in 0..1024 {
3782            ui.panel(RECT, INK).unwrap();
3783        }
3784        assert_eq!(ui.panel(RECT, INK), Err(UiError::Capacity));
3785        let capacities = (ui.commands.capacity(), ui.text.capacity());
3786        println!("shared UI reserved bytes: {}", ui.reserved_bytes());
3787        for i in 0..120 {
3788            next();
3789            begin(&mut ui);
3790            ui.text_fmt(RECT, TextStyle::default(), format_args!("HP {i}"))
3791                .unwrap();
3792            button(&mut ui, 1, true);
3793            ui.finish(true);
3794            ui.paint();
3795        }
3796        assert_eq!((ui.commands.capacity(), ui.text.capacity()), capacities);
3797    }
3798
3799    #[test]
3800    fn responsive_labels_keep_glyph_height_and_only_store_visible_prefixes() {
3801        reset();
3802        crate::edit(|s| {
3803            s.w = 320;
3804            s.h = 240;
3805        });
3806        let mut ui = Ui::new();
3807        ui.begin(Viewport::responsive([320., 240.], [0.; 4]).unwrap());
3808        let long = "X".repeat(100_000);
3809        ui.label(
3810            UiRect {
3811                min: [0.; 2],
3812                size: [60., 16.],
3813            },
3814            &long,
3815            TextStyle {
3816                size: 16.,
3817                ..Default::default()
3818            },
3819        )
3820        .unwrap();
3821        assert_eq!(ui.text, "XX...");
3822        ui.paint();
3823        crate::read(|s| {
3824            assert!(!s.vertices.is_empty());
3825            let bottom = s
3826                .vertices
3827                .iter()
3828                .map(|v| (1. - v[1]) * 120.)
3829                .fold(0_f32, f32::max);
3830            assert!(
3831                (bottom - 14.).abs() < 0.001,
3832                "7 bitmap rows at a 2px cell height"
3833            );
3834            assert!(s.vertices.len() <= ui.vertices);
3835        });
3836        ui.hud_button(
3837            1,
3838            RECT,
3839            &long,
3840            true,
3841            ButtonStyle {
3842                size: 16.,
3843                ..Default::default()
3844            },
3845        )
3846        .unwrap();
3847        assert_eq!(ui.text, "XX...XX..."); // 64px text area fits five glyphs.
3848        let before = (ui.commands.len(), ui.text.len(), ui.vertices);
3849        assert_eq!(
3850            ui.hud_button(1, RECT, &long, true, ButtonStyle::default()),
3851            Err(UiError::DuplicateId)
3852        );
3853        assert_eq!(before, (ui.commands.len(), ui.text.len(), ui.vertices));
3854        assert_eq!(
3855            ui.label(
3856                RECT,
3857                "bad",
3858                TextStyle {
3859                    size: f32::NAN,
3860                    ..Default::default()
3861                }
3862            ),
3863            Err(UiError::InvalidLayout)
3864        );
3865        assert_eq!(before, (ui.commands.len(), ui.text.len(), ui.vertices));
3866    }
3867
3868    #[test]
3869    fn tiny_button_paint_and_focus_never_escape_the_hit_rectangle() {
3870        reset();
3871        crate::edit(|s| {
3872            s.w = 200;
3873            s.h = 200;
3874        });
3875        let mut ui = Ui::new();
3876        for size in [[40., 4.], [1., 1.], [0., 0.]] {
3877            next();
3878            ui.begin(Viewport::responsive([200.; 2], [0.; 4]).unwrap());
3879            let rect = UiRect {
3880                min: [20.; 2],
3881                size,
3882            };
3883            // Existing buttons get the same geometry fix as new HUD buttons.
3884            ui.button(1, rect, "LABEL", true, ButtonStyle::default())
3885                .unwrap();
3886            ui.state.end_frame();
3887            let visible = size[0] > 0. && size[1] > 0.;
3888            assert_eq!(ui.state.focus_next(false), visible.then_some(1));
3889            assert_eq!(ui.state.hit_test([20.; 2]), visible.then_some(1));
3890            assert_eq!(ui.state.hit_test([20. + size[0], 20.]), None);
3891            ui.paint();
3892            crate::read(|s| {
3893                assert_eq!(s.vertices.is_empty(), !visible);
3894                for vertex in &s.vertices {
3895                    let pixel = [(vertex[0] + 1.) * 100., (1. - vertex[1]) * 100.];
3896                    for (axis, coordinate) in pixel.iter().enumerate() {
3897                        assert!(*coordinate >= rect.min[axis] - 0.001);
3898                        assert!(*coordinate <= rect.min[axis] + rect.size[axis] + 0.001);
3899                    }
3900                }
3901                assert!(s.vertices.len() <= ui.vertices);
3902            });
3903        }
3904    }
3905
3906    #[test]
3907    fn responsive_hud_rebuilds_keep_arena_storage_and_hide_empty_viewports() {
3908        reset();
3909        crate::edit(|s| {
3910            s.w = 320;
3911            s.h = 240;
3912        });
3913        let mut ui = Ui::new();
3914        let storage = (ui.commands.as_ptr(), ui.text.as_ptr(), ui.reserved_bytes());
3915        let long = "é日".repeat(10_000);
3916        for width in [320., 180., 40., 1., 0., 320.] {
3917            next();
3918            let viewport = Viewport::responsive([width, 160.], [12.; 4]).unwrap();
3919            ui.begin(viewport);
3920            for (index, rect) in hud_slots(viewport.bounds(), 3, 140., 44., 8.)
3921                .unwrap()
3922                .enumerate()
3923            {
3924                ui.hud_button(index as u64, rect, &long, true, ButtonStyle::default())
3925                    .unwrap();
3926            }
3927            ui.state.end_frame();
3928            let focus = ui.state.focus_next(false);
3929            if viewport.bounds().size[0] == 0. {
3930                assert_eq!(focus, None);
3931                assert_eq!(ui.state.hit_test([0.; 2]), None);
3932            } else {
3933                assert!(focus.is_some());
3934            }
3935            ui.paint();
3936            crate::read(|s| {
3937                if viewport.bounds().size[0] == 0. {
3938                    assert!(s.vertices.is_empty());
3939                }
3940                assert!(s.vertices.len() <= ui.vertices);
3941            });
3942            assert_eq!(
3943                (ui.commands.as_ptr(), ui.text.as_ptr(), ui.reserved_bytes()),
3944                storage
3945            );
3946        }
3947    }
3948}