ferravex_render/ui/
cards.rs

1//! Borrowed menu/result cards in logical UI units, using the existing modal and
2//! atomic composition. Pass bounds inside a responsive viewport's safe area;
3//! coordinates start at zero inside that safe area. Absolute task271 rectangles
4//! use a zero-inset responsive viewport. Fitted viewports scale logical units
5//! and are a caller choice. Fonts never
6//! shrink: title 24, body/stats/actions 18, padding 16, section gaps 12,
7//! action gaps 8 and action height 44.
8//!
9//! Actions keep caller IDs/order/availability. The primary ID must be present,
10//! including when disabled; start/resume/retry and authoritative progression
11//! remain game-owned. `finish_player`/`finish` and paint happen after submission.
12//! A returned action can be queued until an actual simulation tick; cards never
13//! sample gameplay input or own a lifecycle. Controls-open gating stays in Ui.
14//!
15//! Without scrolling, only a complete prefix of sections is submitted. Overflow
16//! paints `CONTENT OMITTED` and reports omitted sections/stat rows. To expose
17//! all copy, reuse task274's pure [`ScrollState`]: set its extents from the layout,
18//! feed accepted/remapped scroll commands outside composition, then submit it.
19//! No new pointer/keyboard routing is installed. Do not enable a `ScrollRegion`
20//! alongside another UI input owner; its documented routing limits still apply.
21//! Scroll translation retains full line rectangles under the content/ancestor
22//! clips. Only intersecting lines are queued, so offscreen copy spends no UI
23//! vertex/text budget. Inspection describes those actual line commands, retaining
24//! UTF-8; bitmap glyph substitution/word wrapping follow [`WrappedText`].
25//!
26//! This executed native/headless recipe composes actual start, pause and results
27//! cards with one/three actions and a disabled action at 320x480 and wide. It
28//! exercises retained paint/inspection, not a GPU, browser or device playtest.
29//!
30//! ```
31//! use ferravex_render::ui::{Ui, UiError, UiLabel, Viewport};
32//! use ferravex_render::ui::cards::{CardAction, CardContent, CardLayout, CardSection};
33//! use ferravex_render::ui::stats::StatRow;
34//! use ferravex_render::input::host_frame;
35//! let mut ui = Ui::new();
36//! ui.set_inspection_enabled(true);
37//! let rows = [StatRow { label: "TIME", value: "1:00.001", description: None }];
38//! let sections = [CardSection::Body("Collect crystals. Return to the entrance."),
39//!                 CardSection::Stats(&rows)];
40//! for width in [320., 960.] {
41//!     for (title, primary, three) in [("CRYSTAL CAVERN", "START", false),
42//!                                    ("PAUSED", "RESUME", true),
43//!                                    ("EXPEDITION COMPLETE", "RETRY", true)] {
44//!         let actions = [CardAction { id: 901, label: primary, enabled: true },
45//!                        CardAction { id: 902, label: "CONTROLS", enabled: true },
46//!                        CardAction { id: 903, label: "NEXT", enabled: false }];
47//!         let viewport = Viewport::responsive([width, 480.], [8., 12., 8., 12.])?;
48//!         let layout = CardLayout::new(viewport.bounds(), CardContent {
49//!             title, sections: &sections, actions: &actions[..if three { 3 } else { 1 }],
50//!             primary: 901, blocker: 900,
51//!         })?;
52//!         host_frame(0., width as u32, 480, || -> Result<(), UiError> {
53//!             ui.begin(viewport);
54//!             let report = ui.card(&layout, None)?;
55//!             assert_eq!(report.omitted_sections, 0);
56//!             ui.finish(true); // No simulation tick is required to render a menu.
57//!             for action in &actions[..if three { 3 } else { 1 }] {
58//!                 let element = ui.inspect().unwrap().find(|e| e.id == Some(action.id)).unwrap();
59//!                 assert_eq!(element.label, UiLabel::Full(action.label));
60//!                 assert_eq!(element.bounds, layout.action_rect(action.id).unwrap());
61//!                 assert_eq!(element.visible_bounds, Some(element.bounds));
62//!                 assert_eq!(element.enabled, action.enabled);
63//!             }
64//!             assert!(!ui.activated(999));
65//!             ui.paint();
66//!             Ok(())
67//!         })?;
68//!     }
69//! }
70//! # Ok::<(), UiError>(())
71//! ```
72//!
73//! Scrolling and nested atomic submission use the same layout. Update scroll
74//! state outside the group; no wheel, pointer, gameplay edge or clock is read.
75//!
76//! ```
77//! use ferravex_play::ui::scroll::ScrollState;
78//! use ferravex_render::ui::{Ui, UiError, Viewport};
79//! use ferravex_render::ui::cards::{CardAction, CardContent, CardLayout, CardSection};
80//! let mut ui = Ui::new();
81//! let viewport = Viewport::responsive([320., 480.], [0.; 4])?;
82//! let copy = "Long briefing. Read before starting.\n".repeat(80);
83//! let sections = [CardSection::Body(&copy)];
84//! let actions = [CardAction { id: 1, label: "START", enabled: true }];
85//! let layout = CardLayout::new(viewport.bounds(), CardContent {
86//!     title: "BRIEFING", sections: &sections, actions: &actions, primary: 1, blocker: 2,
87//! })?;
88//! let mut scroll = ScrollState::new(layout.content_bounds().size[1], layout.content_extent())?;
89//! scroll.page(false); // Feed an accepted remapped menu edge here.
90//! ui.begin(viewport);
91//! let report = ui.compose(|group| layout.submit(group, Some(&scroll)))?;
92//! assert!(report.scrollable);
93//! assert_eq!(report.omitted_sections, 0); // All source remains reachable.
94//! assert_eq!(layout.action_rect(99), None);
95//! ui.paint();
96//! scroll.reset(); // On a new screen/session, caller decides reset semantics.
97//! assert_eq!(scroll.offset(), 0.);
98//! # Ok::<(), UiError>(())
99//! ```
100
101use super::stats::{MAX_STAT_ROWS, StatRow, StatRowsLayout, StatRowsStyle};
102use super::text_layout::{LineLimit, WrappedText};
103use super::{ButtonStyle, PANEL, TextStyle, Ui, UiComposition, UiError, UiRect, WidgetId};
104use ferravex_play::ui::{
105    flow::{self, FlowItem, FlowOptions},
106    scroll::ScrollState,
107};
108
109/// Sections per card; checked before scanning source.
110pub const MAX_CARD_SECTIONS: usize = 8;
111/// Actions per card; all must fit, including disabled actions.
112pub const MAX_CARD_ACTIONS: usize = 8;
113/// Combined UTF-8 bytes in title, sections/stat fields and action labels.
114/// Checked before measurement; stat rows are additionally capped at 64 total.
115pub const MAX_CARD_BYTES: usize = 8192;
116const PAD: f32 = 16.;
117const GAP: f32 = 12.;
118const TITLE: f32 = 24.;
119const TEXT: f32 = 18.;
120const ACTION: f32 = 44.;
121// A bounded source cannot approach this height, even at one scalar per line.
122const MEASURE_HEIGHT: f32 = 1_048_576.;
123const EMPTY: UiRect = UiRect {
124    min: [0.; 2],
125    size: [0.; 2],
126};
127
128/// Borrowed full sections. A non-scrolling overflow omits the entire section,
129/// including every value of a stats section, rather than cropping an essential
130/// value. Use scrolling when that omission is unsuitable for the game.
131#[derive(Clone, Copy, Debug)]
132pub enum CardSection<'a> {
133    Body(&'a str),
134    Stats(&'a [StatRow<'a>]),
135}
136/// Stable caller identity and full single-line label; labels are never ellipsized.
137#[derive(Clone, Copy, Debug)]
138pub struct CardAction<'a> {
139    pub id: WidgetId,
140    pub label: &'a str,
141    pub enabled: bool,
142}
143/// Borrowed content, not retained state. IDs must be unique, including blocker.
144#[derive(Clone, Copy, Debug)]
145pub struct CardContent<'a> {
146    pub title: &'a str,
147    pub sections: &'a [CardSection<'a>],
148    pub actions: &'a [CardAction<'a>],
149    pub primary: WidgetId,
150    pub blocker: WidgetId,
151}
152/// Layout omission, independent of ancestor clips, occlusion and physical pixels.
153#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
154pub struct CardReport {
155    pub omitted_sections: usize,
156    pub omitted_stat_rows: usize,
157    /// Content exceeds its viewport and a matching scroll state was supplied.
158    pub scrollable: bool,
159}
160/// Immutable fixed-storage measured card. Rebuild on copy/bounds changes; no
161/// cache, allocation, input consumption or external mutation occurs in layout.
162#[derive(Debug)]
163pub struct CardLayout<'a> {
164    source: CardContent<'a>,
165    bounds: UiRect,
166    title: UiRect,
167    content: UiRect,
168    notice: Option<UiRect>,
169    actions: [UiRect; MAX_CARD_ACTIONS],
170    sections: [UiRect; MAX_CARD_SECTIONS],
171    extent: f32,
172}
173impl<'a> CardLayout<'a> {
174    /// Validate/measure before insertion. `Capacity` means a section/action/byte/
175    /// total-stat-row bound was exceeded. `DuplicateId` means colliding IDs.
176    /// `InvalidLayout` includes a missing primary, blank title/action, multiline
177    /// action, impossible bounds or unrepresentable geometry. All actions and the
178    /// full title must fit at fixed sizes; insufficient space never inserts a
179    /// partial card. Unknown action queries return `None`. Existing UI budgets
180    /// are checked atomically by submission, not reserved by this pure layout.
181    pub fn new(bounds: UiRect, source: CardContent<'a>) -> Result<Self, UiError> {
182        validate_source(source)?;
183        if !bounds.valid() || bounds.size.iter().any(|v| *v < 2. * PAD) {
184            return Err(UiError::InvalidLayout);
185        }
186        let inside = bounds.inset([PAD; 4])?;
187        let width = inside.size[0];
188        if width < TITLE * 0.75 {
189            return Err(UiError::InvalidLayout);
190        }
191        let title_height = measured(source.title, width, TITLE)?.0;
192        let mut items = [FlowItem::fixed(0.); MAX_CARD_ACTIONS];
193        for (item, action) in items.iter_mut().zip(source.actions) {
194            let minimum = (measured(action.label, f32::MAX, TEXT)?.1 + 32.).max(ACTION);
195            if minimum > width {
196                return Err(UiError::InvalidLayout);
197            }
198            *item = FlowItem {
199                minimum,
200                preferred: minimum,
201                maximum: width,
202                grow: 1.,
203            };
204        }
205        let mut actions = [EMPTY; MAX_CARD_ACTIONS];
206        let report = flow::layout(
207            UiRect {
208                min: [0.; 2],
209                size: [width, MEASURE_HEIGHT],
210            },
211            &items[..source.actions.len()],
212            FlowOptions {
213                row_height: ACTION,
214                ..FlowOptions::default()
215            },
216            &mut actions[..source.actions.len()],
217        )
218        .map_err(|_| UiError::InvalidLayout)?;
219        if report.overflow != 0 {
220            return Err(UiError::InvalidLayout);
221        }
222        let action_height = report.rows as f32 * ACTION + report.rows.saturating_sub(1) as f32 * 8.;
223        let action_top = inside.min[1] + inside.size[1] - action_height;
224        let title = UiRect {
225            min: inside.min,
226            size: [width, title_height],
227        };
228        let content_top = title.min[1] + title.size[1] + GAP;
229        let available = action_top - GAP - content_top;
230        if available < 0. {
231            return Err(UiError::InvalidLayout);
232        }
233        for rect in &mut actions[..source.actions.len()] {
234            rect.min[0] += inside.min[0];
235            rect.min[1] += action_top;
236            // Canonical endpoint extents make intersection with an enclosing
237            // clip idempotent, including fractional flow widths/origins.
238            for axis in 0..2 {
239                rect.size[axis] = (rect.min[axis] + rect.size[axis]) - rect.min[axis];
240            }
241            contained(inside, *rect)?;
242        }
243        contained(inside, title)?;
244        let mut sections = [EMPTY; MAX_CARD_SECTIONS];
245        let mut extent = 0.;
246        for (index, section) in source.sections.iter().enumerate() {
247            let height = match section {
248                CardSection::Body(copy) => measured(copy, width, TEXT)?.0,
249                CardSection::Stats(rows) => stat_layout(width, rows)?.report().required_height,
250            };
251            let top = extent + if index == 0 { 0. } else { GAP };
252            let rect = UiRect {
253                min: [0., top],
254                size: [width, height],
255            };
256            extent = top + height;
257            if !rect.valid() || !extent.is_finite() || extent > MEASURE_HEIGHT {
258                return Err(UiError::InvalidLayout);
259            }
260            sections[index] = rect;
261        }
262        let overflow = extent > available;
263        if overflow && width < measured("CONTENT OMITTED", f32::MAX, TEXT)?.1 {
264            return Err(UiError::InvalidLayout);
265        }
266        let content_height = available - if overflow { TEXT + GAP } else { 0. };
267        if content_height < 0. {
268            return Err(UiError::InvalidLayout);
269        }
270        let content = UiRect {
271            min: [inside.min[0], content_top],
272            size: [width, content_height],
273        };
274        contained(inside, content)?;
275        let notice = overflow.then_some(UiRect {
276            min: [inside.min[0], action_top - GAP - TEXT],
277            size: [width, TEXT],
278        });
279        if let Some(rect) = notice {
280            contained(inside, rect)?;
281        }
282        // Enforce disjoint f32 endpoints rather than trusting subtraction.
283        if title.min[1] + title.size[1] > content.min[1]
284            || content.min[1] + content.size[1] > notice.map_or(action_top, |r| r.min[1])
285            || notice.is_some_and(|r| r.min[1] + r.size[1] > action_top)
286        {
287            return Err(UiError::InvalidLayout);
288        }
289        Ok(Self {
290            source,
291            bounds,
292            title,
293            content,
294            notice,
295            actions,
296            sections,
297            extent,
298        })
299    }
300    /// Card panel in caller logical coordinates.
301    pub fn bounds(&self) -> UiRect {
302        self.bounds
303    }
304    /// Full fixed-size title rectangle.
305    pub fn title_rect(&self) -> UiRect {
306        self.title
307    }
308    /// Viewport for sections; feed its height to task274 `ScrollState`.
309    pub fn content_bounds(&self) -> UiRect {
310        self.content
311    }
312    /// Full content-space height; feed to `ScrollState::set_extents` on reflow.
313    pub fn content_extent(&self) -> f32 {
314        self.extent
315    }
316    /// Unscrolled section rectangle, relative to the content origin.
317    pub fn section_rect(&self, index: usize) -> Option<UiRect> {
318        (index < self.source.sections.len()).then(|| self.sections[index])
319    }
320    /// Exactly the rectangle passed to the painted button and its hit registry.
321    pub fn action_rect(&self, id: WidgetId) -> Option<UiRect> {
322        self.source
323            .actions
324            .iter()
325            .position(|a| a.id == id)
326            .map(|i| self.actions[i])
327    }
328    /// Atomically submit modal, panel, full title, content/notice and every action.
329    /// All interaction, clip and inspection changes roll back through task281.
330    /// Scroll must match both extents exactly and have positive viewport height;
331    /// mismatch fails before insertion. Scroll is borrowed immutably: updating/
332    /// resetting it is caller-owned and lies outside the composition transaction.
333    /// Existing ancestor clips apply unchanged, including to action hits; callers
334    /// must keep the action area inside their visible safe region.
335    pub fn submit(
336        &self,
337        group: &mut UiComposition<'_>,
338        scroll: Option<&ScrollState>,
339    ) -> Result<CardReport, UiError> {
340        group.compose(|group| self.submit_commands(group, scroll))
341    }
342    fn submit_commands(
343        &self,
344        group: &mut UiComposition<'_>,
345        scroll: Option<&ScrollState>,
346    ) -> Result<CardReport, UiError> {
347        if scroll.is_some_and(|s| {
348            s.viewport_extent() != self.content.size[1]
349                || s.content_extent() != self.extent
350                || self.content.size[1] == 0.
351        }) {
352            return Err(UiError::InvalidLayout);
353        }
354        let top = ScrollState::new(self.content.size[1], self.extent)?;
355        let state = scroll.unwrap_or(&top);
356        let mut report = CardReport {
357            scrollable: scroll.is_some() && self.extent > self.content.size[1],
358            ..CardReport::default()
359        };
360        group.modal(self.source.blocker)?;
361        group.panel(self.bounds, PANEL)?;
362        group.wrapped_text(
363            self.title,
364            self.source.title,
365            title_style(),
366            LineLimit::Unlimited,
367        )?;
368        group.push_clip(self.content)?;
369        let mut stopped = false;
370        for (index, section) in self.source.sections.iter().enumerate() {
371            let local = self.sections[index];
372            if scroll.is_none() && (stopped || local.min[1] + local.size[1] > self.content.size[1])
373            {
374                stopped = true;
375                report.omitted_sections += 1;
376                if let CardSection::Stats(rows) = section {
377                    report.omitted_stat_rows += rows.len();
378                }
379                continue;
380            }
381            match section {
382                CardSection::Body(copy) => {
383                    self.paint_block(group, state, local, copy, TextStyle::default())?
384                }
385                CardSection::Stats(rows) => {
386                    let stats = stat_layout(self.content.size[0], rows)?;
387                    let style = StatRowsStyle::default();
388                    for (row, geometry) in rows.iter().zip(stats.rows()) {
389                        for (copy, mut rect, style) in [
390                            Some((row.label, geometry.label, style.label)),
391                            Some((row.value, geometry.value, style.value)),
392                            row.description
393                                .zip(geometry.description)
394                                .map(|(copy, r)| (copy, r, style.description)),
395                        ]
396                        .into_iter()
397                        .flatten()
398                        {
399                            rect.min[1] += local.min[1];
400                            self.paint_block(group, state, rect, copy, style)?;
401                        }
402                    }
403                }
404            }
405        }
406        group.pop_clip()?;
407        if let Some(rect) = self.notice {
408            group.wrapped_text(
409                rect,
410                if scroll.is_some() {
411                    "SCROLL FOR MORE"
412                } else {
413                    "CONTENT OMITTED"
414                },
415                TextStyle::default(),
416                LineLimit::Unlimited,
417            )?;
418        }
419        for (action, rect) in self.source.actions.iter().zip(self.actions) {
420            // button, not legacy scaled text or an ellipsized HUD label. Layout
421            // already proved the full label fits at size 18 with 32-unit padding.
422            group.button(
423                action.id,
424                rect,
425                action.label,
426                action.enabled,
427                ButtonStyle::default(),
428            )?;
429        }
430        Ok(report)
431    }
432    fn paint_block(
433        &self,
434        group: &mut UiComposition<'_>,
435        state: &ScrollState,
436        rect: UiRect,
437        copy: &str,
438        style: TextStyle,
439    ) -> Result<(), UiError> {
440        let translated = state.translate_rect(self.content, rect)?;
441        let wrapped = WrappedText::new(copy, rect.size[0], style.size)?;
442        for (index, line) in wrapped.lines().enumerate() {
443            let line_rect = UiRect {
444                min: [
445                    translated.min[0],
446                    translated.min[1] + index as f32 * style.size,
447                ],
448                size: [rect.size[0], style.size],
449            };
450            if line_rect.intersect(self.content).is_some() {
451                // Full logical line rectangle is preserved. The clip, not a
452                // cropped rectangle, determines partial scroll visibility.
453                group.wrapped_text(line_rect, line.text, style, LineLimit::Unlimited)?;
454            }
455        }
456        Ok(())
457    }
458}
459impl Ui {
460    /// Standalone atomic card submission. See the module's executed recipe;
461    /// use [`CardLayout::submit`] inside a larger atomic composition.
462    pub fn card(
463        &mut self,
464        layout: &CardLayout<'_>,
465        scroll: Option<&ScrollState>,
466    ) -> Result<CardReport, UiError> {
467        self.compose(|group| layout.submit_commands(group, scroll))
468    }
469}
470fn title_style() -> TextStyle {
471    TextStyle {
472        size: TITLE,
473        ..TextStyle::default()
474    }
475}
476fn measured(copy: &str, width: f32, size: f32) -> Result<(f32, f32), UiError> {
477    let m = WrappedText::new(copy, width, size)?.measure();
478    Ok((m.height.max(size), m.width))
479}
480fn stat_layout<'a>(width: f32, rows: &'a [StatRow<'a>]) -> Result<StatRowsLayout<'a>, UiError> {
481    StatRowsLayout::new(
482        UiRect {
483            min: [0.; 2],
484            size: [width, MEASURE_HEIGHT],
485        },
486        rows,
487        StatRowsStyle::default(),
488    )
489}
490fn validate_source(source: CardContent<'_>) -> Result<(), UiError> {
491    if source.sections.len() > MAX_CARD_SECTIONS || source.actions.len() > MAX_CARD_ACTIONS {
492        return Err(UiError::Capacity);
493    }
494    let mut bytes = source.title.len();
495    let mut rows_count: usize = 0;
496    let mut add = |copy: &str| -> Result<(), UiError> {
497        bytes = bytes.checked_add(copy.len()).ok_or(UiError::Capacity)?;
498        if bytes > MAX_CARD_BYTES {
499            return Err(UiError::Capacity);
500        }
501        Ok(())
502    };
503    add("")?;
504    for section in source.sections {
505        match section {
506            CardSection::Body(copy) => add(copy)?,
507            CardSection::Stats(rows) => {
508                rows_count = rows_count
509                    .checked_add(rows.len())
510                    .ok_or(UiError::Capacity)?;
511                if rows_count > MAX_STAT_ROWS {
512                    return Err(UiError::Capacity);
513                }
514                for row in *rows {
515                    add(row.label)?;
516                    add(row.value)?;
517                    if let Some(d) = row.description {
518                        add(d)?;
519                    }
520                }
521            }
522        }
523    }
524    for action in source.actions {
525        add(action.label)?;
526    }
527    if source.title.trim().is_empty() || !source.actions.iter().any(|a| a.id == source.primary) {
528        return Err(UiError::InvalidLayout);
529    }
530    for (i, action) in source.actions.iter().enumerate() {
531        if action.id == source.blocker || source.actions[..i].iter().any(|a| a.id == action.id) {
532            return Err(UiError::DuplicateId);
533        }
534        if action.label.trim().is_empty()
535            || action.label.chars().any(char::is_control)
536            || action.label.contains('\u{2028}')
537            || action.label.contains('\u{2029}')
538        {
539            return Err(UiError::InvalidLayout);
540        }
541    }
542    Ok(())
543}
544fn contained(bounds: UiRect, rect: UiRect) -> Result<(), UiError> {
545    if !rect.valid()
546        || (0..2).any(|a| {
547            rect.min[a] < bounds.min[a]
548                || rect.min[a] + rect.size[a] > bounds.min[a] + bounds.size[a]
549                || (rect.size[a] > 0. && rect.min[a] + rect.size[a] <= rect.min[a])
550        })
551    {
552        return Err(UiError::InvalidLayout);
553    }
554    Ok(())
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560    use crate::input::{ActionKind, Binding, InputCode, PlayerInput, host_frame};
561
562    const ACTIONS: [CardAction<'static>; 3] = [
563        CardAction {
564            id: 10,
565            label: "RESUME",
566            enabled: true,
567        },
568        CardAction {
569            id: 20,
570            label: "CONTROLS",
571            enabled: false,
572        },
573        CardAction {
574            id: 30,
575            label: "RETRY",
576            enabled: true,
577        },
578    ];
579    fn reset() {
580        crate::edit(|s| {
581            *s = crate::State::default();
582            s.w = 1000;
583            s.h = 600;
584        });
585    }
586    fn viewport() -> super::super::Viewport {
587        super::super::Viewport::responsive([1000., 600.], [0.; 4]).unwrap()
588    }
589    fn card<'a>(sections: &'a [CardSection<'a>], actions: &'a [CardAction<'a>]) -> CardLayout<'a> {
590        CardLayout::new(
591            UiRect {
592                min: [16.; 2],
593                size: [600., 480.],
594            },
595            CardContent {
596                title: "PAUSED",
597                sections,
598                actions,
599                primary: 10,
600                blocker: 9,
601            },
602        )
603        .unwrap()
604    }
605    fn point(rect: UiRect) -> [f32; 2] {
606        [rect.min[0] + 2., rect.min[1] + 2.]
607    }
608    fn mouse(point: [f32; 2], pressed: bool) {
609        crate::pointer(point[0], point[1], 0., 0.);
610        crate::button(1, pressed);
611    }
612    fn draw(ui: &mut Ui, card: &CardLayout<'_>) {
613        ui.begin(viewport());
614        ui.card(card, None).unwrap();
615    }
616
617    #[test]
618    fn journey400_277_capture_release_controls_focus_disabled_and_ancestor_hit_geometry() {
619        reset();
620        let mut ui = Ui::new();
621        ui.set_inspection_enabled(true);
622        let layout = card(&[], &ACTIONS);
623        let first = layout.action_rect(10).unwrap();
624        let last = layout.action_rect(30).unwrap();
625        host_frame(0., 1000, 600, || {
626            draw(&mut ui, &layout);
627            mouse(point(first), true);
628            ui.finish(true);
629            assert_eq!(ui.interaction().pointer_capture, Some(10));
630            assert!(!ui.activated(10));
631        });
632        // Ordinary card reconstruction preserves the captured stable ID, but
633        // releasing over a different painted action does not activate either.
634        host_frame(0., 1000, 600, || {
635            draw(&mut ui, &layout);
636            mouse(point(last), false);
637            ui.finish(true);
638            assert!(!ui.activated(10) && !ui.activated(30));
639        });
640        for block in [false, true] {
641            host_frame(0., 1000, 600, || {
642                draw(&mut ui, &layout);
643                mouse(point(first), true);
644                ui.finish(true);
645                assert_eq!(ui.interaction().pointer_capture, Some(10));
646            });
647            host_frame(0., 1000, 600, || {
648                draw(&mut ui, &layout);
649                crate::edit(|s| s.controls_open = block);
650                mouse(point(first), false);
651                ui.finish(true);
652                assert_eq!(ui.activated(10), !block);
653                assert_eq!(ui.interaction().input_blocked, block);
654                crate::edit(|s| s.controls_open = false);
655            });
656            host_frame(0., 1000, 600, || {
657                draw(&mut ui, &layout);
658                ui.finish(true);
659                assert!(!ui.activated(10), "a release activates only once");
660            });
661        }
662        // Disabled primary eligibility is caller-owned and cannot be revived
663        // by a held pointer after availability changes.
664        host_frame(0., 1000, 600, || {
665            draw(&mut ui, &layout);
666            mouse(point(first), true);
667            ui.finish(true);
668        });
669        let disabled = [
670            CardAction {
671                enabled: false,
672                ..ACTIONS[0]
673            },
674            ACTIONS[1],
675            ACTIONS[2],
676        ];
677        host_frame(0., 1000, 600, || {
678            draw(&mut ui, &card(&[], &disabled));
679            mouse(point(first), false);
680            ui.finish(true);
681            assert!(!ui.activated(10));
682        });
683        host_frame(0., 1000, 600, || {
684            draw(&mut ui, &layout);
685            // Previous disabled-primary frame auto-focused RETRY. Two Tabs
686            // traverse RESUME and then RETRY, skipping disabled CONTROLS.
687            crate::key(0xff09, true);
688            crate::key(0xff09, false);
689            crate::key(0xff09, true);
690            crate::key(0xff09, false);
691            crate::key(0xff0d, true);
692            crate::key(0xff0d, false);
693            ui.finish(true);
694            assert_eq!(ui.focused(), Some(30));
695            assert!(ui.activated(30));
696            assert!(!ui.activated(20));
697        });
698        // A smaller ancestor clips paint and hits at the identical half-open
699        // edge; clicking the hidden half reaches only the existing modal.
700        let clip = UiRect {
701            min: first.min,
702            size: [first.size[0] / 2., 44.],
703        };
704        for visible in [false, true] {
705            host_frame(0., 1000, 600, || {
706                ui.begin(viewport());
707                ui.push_clip(clip).unwrap();
708                ui.card(&layout, None).unwrap();
709                ui.pop_clip();
710                let p = if visible {
711                    point(clip)
712                } else {
713                    [clip.min[0] + clip.size[0], clip.min[1] + 2.]
714                };
715                mouse(p, true);
716                mouse(p, false);
717                ui.finish(true);
718                assert_eq!(ui.activated(10), visible);
719                let actual = ui.inspect().unwrap().find(|e| e.id == Some(10)).unwrap();
720                assert_eq!(actual.bounds, first);
721                assert_eq!(actual.visible_bounds, first.intersect(clip));
722                ui.paint();
723            });
724        }
725        // Blur cancels an in-progress captured gesture.
726        host_frame(0., 1000, 600, || {
727            draw(&mut ui, &layout);
728            mouse(point(first), true);
729            ui.finish(true);
730        });
731        host_frame(0., 1000, 600, || {
732            draw(&mut ui, &layout);
733            crate::edit(|s| s.input.focus(false));
734            ui.finish(true);
735        });
736        host_frame(0., 1000, 600, || {
737            draw(&mut ui, &layout);
738            crate::edit(|s| s.input.focus(true));
739            mouse(point(first), false);
740            ui.finish(true);
741            assert!(!ui.activated(10));
742        });
743    }
744
745    #[test]
746    fn journey400_277_failed_modal_preserves_prior_capture_focus_and_emitted_paint() {
747        reset();
748        let mut ui = Ui::new();
749        ui.set_inspection_enabled(true);
750        let layout = card(&[CardSection::Body("COPY")], &ACTIONS);
751        let prior = UiRect {
752            min: [8.; 2],
753            size: [120., 44.],
754        };
755        host_frame(0., 1000, 600, || {
756            ui.begin(viewport());
757            ui.button(1, prior, "PRIOR", true, ButtonStyle::default())
758                .unwrap();
759            mouse(point(prior), true);
760            ui.finish(true);
761            assert_eq!(ui.focused(), Some(1));
762            assert_eq!(ui.interaction().pointer_capture, Some(1));
763        });
764        host_frame(0., 1000, 600, || {
765            ui.begin(viewport());
766            ui.button(1, prior, "PRIOR", true, ButtonStyle::default())
767                .unwrap();
768            ui.paint();
769            let before = crate::read(|s| s.vertices.clone());
770            let mut inspection = [0; 8192];
771            let bytes = ui.write_inspection(&mut inspection).unwrap();
772            assert_eq!(
773                ui.compose(|g| {
774                    layout.submit(g, None)?;
775                    // A later duplicate primary rejects panel/title/body/actions and
776                    // modal together; it cannot replace the prior capture.
777                    g.button(10, prior, "DUPLICATE", true, ButtonStyle::default())
778                }),
779                Err(UiError::DuplicateId)
780            );
781            let mut after_inspection = [0; 8192];
782            let after_bytes = ui.write_inspection(&mut after_inspection).unwrap();
783            assert_eq!(bytes, after_bytes);
784            assert_eq!(inspection[..bytes], after_inspection[..after_bytes]);
785            crate::edit(|s| s.vertices.clear());
786            ui.paint();
787            assert_eq!(crate::read(|s| s.vertices.clone()), before);
788            mouse(point(prior), false);
789            ui.finish(true);
790            assert!(ui.activated(1));
791            assert!(!ui.activated(10) && !ui.activated(9));
792        });
793    }
794
795    #[test]
796    fn journey400_277_remapped_confirm_does_not_consume_zero_tick_gameplay_edges() {
797        reset();
798        let layout = card(&[], &ACTIONS);
799        let mut ui = Ui::new();
800        let mut player = PlayerInput::transient("journey400-card-ticks");
801        player
802            .global_action(
803                "confirm",
804                "Confirm",
805                ActionKind::Button,
806                vec![Binding::digital(InputCode::Key(106))],
807            )
808            .unwrap();
809        player
810            .action(
811                "jump",
812                "Jump",
813                ActionKind::Button,
814                vec![Binding::digital(InputCode::Key(107))],
815            )
816            .unwrap();
817        host_frame(0., 1000, 600, || {
818            player.sample(true);
819            draw(&mut ui, &layout);
820            ui.finish_player(&mut player, true);
821        });
822        host_frame(0., 1000, 600, || {
823            crate::key(106, true);
824            crate::key(106, false);
825            crate::key(107, true);
826            crate::key(107, false);
827            player.sample(true);
828            draw(&mut ui, &layout);
829            ui.finish_player(&mut player, true);
830            assert!(ui.activated(10));
831            // Zero simulation ticks: leave jump's buffered edges untouched.
832        });
833        host_frame(0., 1000, 600, || {
834            player.sample(true);
835            draw(&mut ui, &layout);
836            ui.finish_player(&mut player, true);
837            assert!(!ui.activated(10));
838            let first = player.take_tick(["jump"])[0];
839            assert!(first.pressed && first.released);
840            let second = player.take_tick(["jump"])[0];
841            assert!(!second.pressed && !second.released);
842        });
843    }
844
845    #[test]
846    fn journey400_277_visible_line_paint_equals_full_wrapped_stat_composition() {
847        let copy = "ALPHA BETA GAMMA\n\né日 Z\nLONGWORDSREMAINATFIXEDSIZE".repeat(8);
848        let rows = [
849            StatRow {
850                label: "TOTAL\nACCEPTED",
851                value: "18446744073709551615",
852                description: Some("é日 RESULT\nMORE DETAILS"),
853            },
854            StatRow {
855                label: "TIME",
856                value: "1:00.001",
857                description: None,
858            },
859        ];
860        let sections = [CardSection::Body(&copy), CardSection::Stats(&rows)];
861        for width in [288., 920.] {
862            for offset in [0., 9.5, f32::MAX] {
863                reset();
864                let layout = CardLayout::new(
865                    UiRect {
866                        min: [12.25, 16.5],
867                        size: [width, 480.],
868                    },
869                    CardContent {
870                        title: "RESULT",
871                        sections: &sections,
872                        actions: &ACTIONS,
873                        primary: 10,
874                        blocker: 9,
875                    },
876                )
877                .unwrap();
878                let mut scroll = ScrollState::new(layout.content.size[1], layout.extent).unwrap();
879                scroll.set_offset(offset).unwrap();
880                let mut ui = Ui::new();
881                ui.begin(viewport());
882                ui.card(&layout, Some(&scroll)).unwrap();
883                ui.paint();
884                let actual = crate::read(|s| s.vertices.clone());
885                crate::edit(|s| s.vertices.clear());
886                ui.begin(viewport());
887                ui.compose(|g| {
888                    g.modal(9)?;
889                    g.panel(layout.bounds, PANEL)?;
890                    g.wrapped_text(layout.title, "RESULT", title_style(), LineLimit::Unlimited)?;
891                    g.push_clip(layout.content)?;
892                    for (i, section) in sections.iter().enumerate() {
893                        let local = layout.sections[i];
894                        match section {
895                            CardSection::Body(copy) => {
896                                g.wrapped_text(
897                                    scroll.translate_rect(layout.content, local)?,
898                                    copy,
899                                    TextStyle::default(),
900                                    LineLimit::Unlimited,
901                                )?;
902                            }
903                            CardSection::Stats(rows) => {
904                                for (row, geometry) in rows
905                                    .iter()
906                                    .zip(stat_layout(layout.content.size[0], rows)?.rows())
907                                {
908                                    for (copy, mut rect) in [
909                                        Some((row.label, geometry.label)),
910                                        Some((row.value, geometry.value)),
911                                        row.description.zip(geometry.description),
912                                    ]
913                                    .into_iter()
914                                    .flatten()
915                                    {
916                                        rect.min[1] += local.min[1];
917                                        g.wrapped_text(
918                                            scroll.translate_rect(layout.content, rect)?,
919                                            copy,
920                                            TextStyle::default(),
921                                            LineLimit::Unlimited,
922                                        )?;
923                                    }
924                                }
925                            }
926                        }
927                    }
928                    g.pop_clip()?;
929                    if let Some(rect) = layout.notice {
930                        g.wrapped_text(
931                            rect,
932                            "SCROLL FOR MORE",
933                            TextStyle::default(),
934                            LineLimit::Unlimited,
935                        )?;
936                    }
937                    for (action, rect) in ACTIONS.iter().zip(layout.actions) {
938                        g.button(
939                            action.id,
940                            rect,
941                            action.label,
942                            action.enabled,
943                            ButtonStyle::default(),
944                        )?;
945                    }
946                    Ok(())
947                })
948                .unwrap();
949                ui.paint();
950                assert_eq!(
951                    crate::read(|s| s.vertices.clone()),
952                    actual,
953                    "width={width} offset={offset}"
954                );
955            }
956        }
957    }
958}