ferravex_render/ui/
scroll.rs

1//! A bounded vertical region composed from the existing [`UiState`] and [`Ui`].
2//!
3//! Keep one [`ScrollRegion`] and a dedicated paint-only `Ui` across frames. Pass
4//! all content items (including offscreen ones) to `update`, then queue labels
5//! and buttons using the resulting offset. Do **not** call `Ui::finish` on that
6//! paint-only UI: the region owns its focus/capture and reads the ordered host
7//! journal itself. Other menus keep their own `Ui` and focus. The caller enables
8//! only the active input owner; overlapping/nested scroll routing is unsupported.
9//!
10//! All coordinates are logical UI units. A responsive viewport keeps fonts in
11//! host logical pixels; use a zero-inset viewport with absolute `HudRegions`
12//! rectangles. A fitted viewport is also supported: input is unprojected once.
13//! No simulation clock, gameplay edge, camera or renderer is replaced.
14//!
15//! ```
16//! use ferravex_render::ui::{ButtonStyle, Ui, UiRect, Viewport};
17//! use ferravex_render::ui::scroll::{ScrollItem, ScrollRegion};
18//! let viewport = Viewport::responsive([320., 240.], [0.; 4])?;
19//! let bounds = UiRect { min: [12., 32.], size: [296., 100.] };
20//! let items = [10, 20, 30].map(|id| ScrollItem {
21//!     id, rect: UiRect { min: [0., (id / 10 - 1) as f32 * 70.], size: [296., 44.] },
22//!     enabled: true,
23//! });
24//! let mut region = ScrollRegion::new(3);
25//! let mut paint = Ui::new(); // Reuse both between frames.
26//! region.update(viewport, bounds, 184., &items, true)?;
27//! assert_eq!(region.focus_next(false), Some(10));
28//! assert_eq!(region.focus_next(false), Some(20));
29//! assert_eq!(region.focus_next(false), Some(30));
30//! assert_eq!(region.scroll().offset(), 84.);
31//! paint.begin(viewport);
32//! for (item, label) in items.iter().zip(["COURSE", "BEST TIME", "CONTROLS"]) {
33//!     region.button(&mut paint, item.id, label, ButtonStyle::default())?;
34//! }
35//! // In a host frame: paint.paint(); inspect region.activated(item.id).
36//! // For remapped confirmation: call activate_focused only on its accepted edge.
37//! assert_eq!(region.activate_focused(), Some(30));
38//! assert!(region.activated(30));
39//! # Ok::<(), ferravex_render::ui::UiError>(())
40//! ```
41
42use super::{ButtonStyle, Ui, UiError, UiRect, Viewport, WidgetId};
43use crate::input::{InputCode, MAX_EVENTS, PlatformEvent, touch};
44use ferravex_play::ui::{UiState, Widget, scroll::ScrollState};
45
46/// Region item ceiling, additionally subject to the paint UI's command/text budgets.
47pub const SCROLL_ITEM_CAPACITY: usize = 1024;
48
49/// A stable identity and unscrolled content-space rectangle. Items must fit the
50/// declared content width/height. Disabled items still occlude pointer hits.
51/// Slice order defines Tab/arrow order and back-to-front pointer hit order.
52#[derive(Clone, Copy, Debug, PartialEq)]
53pub struct ScrollItem {
54    pub id: WidgetId,
55    pub rect: UiRect,
56    pub enabled: bool,
57}
58
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60enum Pointer {
61    Mouse,
62    Touch(u64),
63}
64
65#[derive(Clone, Copy, Debug)]
66struct Drag {
67    pointer: Pointer,
68    start: [f32; 2],
69    offset: f32,
70    moved: bool,
71}
72
73/// Bounded content registry with the existing UI's press/release capture rules.
74/// Construction reserves storage once; update/navigation/drag do not grow it.
75/// Focus survives scrolling and cancellation. Resize/reflow cancels a pending
76/// press, preserves eligible focus IDs, and clamps the offset without activation.
77pub struct ScrollRegion {
78    scroll: ScrollState,
79    state: UiState,
80    items: Vec<ScrollItem>,
81    viewport: Viewport,
82    bounds: UiRect,
83    drag: Option<Drag>,
84    active: Option<WidgetId>,
85    frame: Option<u64>,
86    epoch: u64,
87    shift: u8,
88    gamepad: u8,
89    pad_epoch: Option<(u8, u32)>,
90    accepting: bool,
91    mouse: Option<[f32; 2]>,
92}
93
94impl ScrollRegion {
95    /// Reserve at most [`SCROLL_ITEM_CAPACITY`] items; zero capacity is legal.
96    /// See the module recipe for the update-before-paint lifecycle.
97    pub fn new(capacity: usize) -> Self {
98        let capacity = capacity.min(SCROLL_ITEM_CAPACITY);
99        let viewport = Viewport::responsive([0.; 2], [0.; 4]).unwrap();
100        Self {
101            scroll: ScrollState::default(),
102            state: UiState::with_capacity(capacity),
103            items: Vec::with_capacity(capacity),
104            viewport,
105            bounds: viewport.bounds(),
106            drag: None,
107            active: None,
108            frame: None,
109            epoch: 0,
110            shift: 0,
111            gamepad: 0,
112            pad_epoch: None,
113            accepting: false,
114            mouse: None,
115        }
116    }
117
118    pub fn capacity(&self) -> usize {
119        self.state.capacity()
120    }
121
122    pub fn scroll(&self) -> &ScrollState {
123        &self.scroll
124    }
125
126    pub fn bounds(&self) -> UiRect {
127        self.bounds
128    }
129
130    pub fn focused(&self) -> Option<WidgetId> {
131        self.state.focused()
132    }
133
134    pub fn activated(&self, id: WidgetId) -> bool {
135        self.active == Some(id)
136    }
137
138    /// Select the player's controller (0..4). New/reconnected pads need a fresh
139    /// edge after their first update, matching the existing `Ui` adapter.
140    pub fn set_gamepad(&mut self, pad: u8) -> Result<(), UiError> {
141        if pad >= 4 {
142            return Err(UiError::InvalidLayout);
143        }
144        if self.gamepad != pad {
145            self.gamepad = pad;
146            self.pad_epoch = None;
147        }
148        Ok(())
149    }
150
151    /// Validate/rebuild content, then handle the current host journal once.
152    ///
153    /// Wheel uses 40 logical units per host notch, positive host wheel meaning
154    /// up. Mouse/one-touch drags start anywhere inside the region, cancel child
155    /// clicks after six logical units of movement, and continue outside it.
156    /// Tab/arrows and selected-pad D-pad reveal focus; Page Up/Down move one
157    /// viewport, Home/End move to the boundaries. Enter/pad A confirm. Feed
158    /// remapped edges through `focus_next`, `page`, and `activate_focused`.
159    ///
160    /// Bounds must be inside `viewport.bounds()`. Items must be unique and fully
161    /// inside the declared content. Errors preserve the old layout/offset/focus
162    /// but cancel capture/activation and disable acceptance until a valid update.
163    /// Hidden, disabled, host-unfocused, journal-overflow and settings-editor
164    /// frames cancel gestures. Duplicate calls in a host frame do not replay
165    /// events and clear the previous activation result.
166    pub fn update(
167        &mut self,
168        viewport: Viewport,
169        bounds: UiRect,
170        content_extent: f32,
171        items: &[ScrollItem],
172        enabled: bool,
173    ) -> Result<(), UiError> {
174        self.active = None;
175        let mut next_scroll = self.scroll;
176        let validation = (|| {
177            next_scroll.set_extents(bounds.size[1], content_extent)?;
178            if !bounds.valid()
179                || (0..2).any(|axis| {
180                    bounds.min[axis] < viewport.bounds().min[axis]
181                        || bounds.min[axis] as f64 + bounds.size[axis] as f64
182                            > viewport.bounds().min[axis] as f64
183                                + viewport.bounds().size[axis] as f64
184                })
185            {
186                return Err(UiError::InvalidLayout);
187            }
188            if items.len() > self.capacity() {
189                return Err(UiError::Capacity);
190            }
191            for (index, item) in items.iter().enumerate() {
192                next_scroll.translate_rect(bounds, item.rect)?;
193                if items[..index].iter().any(|old| old.id == item.id) {
194                    return Err(UiError::DuplicateId);
195                }
196            }
197            Ok(())
198        })();
199        if let Err(error) = validation {
200            self.cancel();
201            self.accepting = false;
202            // A repaired layout must not replay the packet that failed admission.
203            self.frame = Some(crate::read(|s| s.frame));
204            return Err(error);
205        }
206        let changed = self.bounds != bounds
207            || self.viewport.bounds() != viewport.bounds()
208            || self.viewport.pixels() != viewport.pixels()
209            || self.viewport.scale() != viewport.scale()
210            || self.scroll.content_extent() != content_extent
211            || self.items != items;
212        if changed {
213            self.cancel();
214        }
215        self.scroll = next_scroll;
216        self.viewport = viewport;
217        self.bounds = bounds;
218        self.items.clear();
219        self.items.extend_from_slice(items);
220        self.state.begin_frame();
221        for item in items {
222            self.state.add(Widget {
223                id: item.id,
224                rect: item.rect,
225                clip: None,
226                enabled: item.enabled,
227                focusable: true,
228            })?; // Geometry, duplicates and capacity were preflighted above.
229        }
230        self.state.end_frame();
231
232        let mut events = [PlatformEvent::None; MAX_EVENTS];
233        let (frame, epoch, focused, overflow, blocked, pointer, pad_epoch) = crate::read(|s| {
234            let source = s.input.events();
235            events[..source.len()].copy_from_slice(source);
236            (
237                s.frame,
238                s.input.focus_epoch,
239                s.input.focused,
240                s.input.overflow,
241                s.controls_open,
242                [s.mouse.x, s.mouse.y],
243                s.input.pads[self.gamepad as usize]
244                    .connected
245                    .then_some((self.gamepad, s.input.pads[self.gamepad as usize].epoch)),
246            )
247        });
248        let fresh_pad = self.pad_epoch != pad_epoch;
249        self.pad_epoch = pad_epoch;
250        self.accepting = enabled
251            && focused
252            && !overflow
253            && !blocked
254            && bounds.size.iter().all(|size| *size > 0.);
255        if epoch != self.epoch || !self.accepting {
256            self.cancel();
257            self.shift = 0;
258        }
259        self.epoch = epoch;
260        if self.frame == Some(frame) {
261            return Ok(());
262        }
263        self.frame = Some(frame);
264        if !self.accepting {
265            return Ok(());
266        }
267        // Absolute positions are journaled at button edges. Between them the
268        // existing host supplies relative motion and a final absolute sample.
269        let final_pointer = pointer;
270        let mut pointer = self.mouse.unwrap_or(final_pointer);
271        self.mouse = Some(final_pointer);
272        for event in events {
273            match event {
274                PlatformEvent::None => break,
275                PlatformEvent::PointerPosition(p) => {
276                    pointer = p.to_array();
277                    self.move_pointer(Pointer::Mouse, pointer);
278                }
279                PlatformEvent::MouseMotion(delta) => {
280                    pointer[0] += delta.x;
281                    pointer[1] += delta.y;
282                    self.move_pointer(Pointer::Mouse, pointer);
283                }
284                PlatformEvent::Value(InputCode::Mouse(1), value) => {
285                    if value >= 0.5 {
286                        self.press(Pointer::Mouse, pointer);
287                    } else {
288                        self.release(Pointer::Mouse, pointer);
289                    }
290                }
291                PlatformEvent::Touch(event) => {
292                    let owner = Pointer::Touch(event.id);
293                    let point = event.position.to_array();
294                    match event.phase {
295                        touch::Phase::Start => self.press(owner, point),
296                        touch::Phase::Move => self.move_pointer(owner, point),
297                        touch::Phase::End => self.release(owner, point),
298                        touch::Phase::Cancel => {
299                            if self.drag.is_some_and(|drag| drag.pointer == owner) {
300                                self.cancel();
301                            }
302                        }
303                    }
304                }
305                PlatformEvent::Value(InputCode::Wheel(1), value) => {
306                    if self
307                        .local_point(final_pointer)
308                        .is_some_and(|p| self.bounds.contains(p))
309                    {
310                        // Host values are finite and capped at 1000; retain a
311                        // finite delta even for a directly injected journal.
312                        if value.is_finite() {
313                            let _ = self.scroll_by(-value.clamp(-1000., 1000.) * 40.);
314                        }
315                    }
316                }
317                PlatformEvent::Value(InputCode::Key(key @ (0xffe1 | 0xffe2)), value) => {
318                    let bit = if key == 0xffe1 { 1 } else { 2 };
319                    if value >= 0.5 {
320                        self.shift |= bit;
321                    } else {
322                        self.shift &= !bit;
323                    }
324                }
325                PlatformEvent::Value(InputCode::Key(key), value) if value >= 0.5 => match key {
326                    0xff09 => {
327                        self.focus_next(self.shift != 0);
328                    }
329                    0xff54 | 0xff53 => {
330                        self.focus_next(false);
331                    }
332                    0xff52 | 0xff51 => {
333                        self.focus_next(true);
334                    }
335                    0xff55 => {
336                        self.page(true);
337                    }
338                    0xff56 => {
339                        self.page(false);
340                    }
341                    0xff50 => {
342                        let _ = self.scroll_by(-f32::MAX);
343                    }
344                    0xff57 => {
345                        let _ = self.scroll_by(f32::MAX);
346                    }
347                    0xff0d => {
348                        self.activate_focused();
349                    }
350                    0xff1b => self.cancel(),
351                    _ => {}
352                },
353                PlatformEvent::Pad {
354                    index,
355                    code: InputCode::PadButton(button),
356                    value,
357                } if index == self.gamepad && !fresh_pad && value >= 0.5 => match button {
358                    12 | 14 => {
359                        self.focus_next(true);
360                    }
361                    13 | 15 => {
362                        self.focus_next(false);
363                    }
364                    0 => {
365                        self.activate_focused();
366                    }
367                    _ => {}
368                },
369                _ => {}
370            }
371        }
372        self.move_pointer(Pointer::Mouse, final_pointer);
373        Ok(())
374    }
375
376    /// Submission-order navigation including offscreen items, with wrap and
377    /// disabled/zero-area skipping inherited from `UiState`. Reveals the result
378    /// before the next paint; does not activate it or change another UI's focus.
379    pub fn focus_next(&mut self, reverse: bool) -> Option<WidgetId> {
380        self.cancel();
381        let id = self.state.focus_next(reverse)?;
382        self.reveal(id);
383        Some(id)
384    }
385
386    /// Reveal a registered enabled, nonempty item without selecting or activating
387    /// it. Unknown/disabled IDs return false. Returns whether the offset changed.
388    pub fn reveal(&mut self, id: WidgetId) -> bool {
389        let Some(item) = self.items.iter().find(|item| {
390            item.id == id && item.enabled && item.rect.size.iter().all(|size| *size > 0.)
391        }) else {
392            return false;
393        };
394        let changed = self
395            .scroll
396            .ensure_visible(item.rect.min[1], item.rect.size[1])
397            .unwrap_or(false);
398        if changed {
399            self.cancel();
400        }
401        changed
402    }
403
404    /// Explicit/remapped scroll input. Cancels a pending click even at an exhausted
405    /// boundary. Nonfinite deltas fail without moving or canceling anything.
406    pub fn scroll_by(&mut self, delta: f32) -> Result<bool, UiError> {
407        let changed = self.scroll.scroll_by(delta)?;
408        self.cancel();
409        Ok(changed)
410    }
411
412    /// Explicit/remapped Page Up/Down, retaining focus without activating a row.
413    pub fn page(&mut self, reverse: bool) -> bool {
414        self.cancel();
415        self.scroll.page(reverse)
416    }
417
418    /// Confirm the focused visible item while input is enabled. If focus is
419    /// entirely clipped (for example after Page Down), reveal it and return
420    /// `None`; another edge is required to activate. No focus is auto-created.
421    pub fn activate_focused(&mut self) -> Option<WidgetId> {
422        if !self.accepting {
423            return None;
424        }
425        let id = self.state.activate_focused()?;
426        if self.rect(id)?.intersect(self.bounds).is_none() {
427            self.reveal(id);
428            return None;
429        }
430        self.active = Some(id);
431        Some(id)
432    }
433
434    /// Current translated geometry; clip it against `bounds()` for paint.
435    pub fn rect(&self, id: WidgetId) -> Option<UiRect> {
436        let item = self.items.iter().find(|item| item.id == id)?;
437        self.scroll.translate_rect(self.bounds, item.rect).ok()
438    }
439
440    /// Queue a registered item using the existing fixed-size HUD button and clip
441    /// stack. The focused item uses the style's focus fill and original fill ink.
442    /// This is paint only: inspect this region's `activated`, not `Ui::activated`.
443    /// On queue failure the clip is still popped; earlier paint commands remain.
444    pub fn button(
445        &self,
446        ui: &mut Ui,
447        id: WidgetId,
448        label: &str,
449        mut style: ButtonStyle,
450    ) -> Result<(), UiError> {
451        let item = self
452            .items
453            .iter()
454            .find(|item| item.id == id)
455            .ok_or(UiError::InvalidLayout)?;
456        let rect = self.rect(id).ok_or(UiError::InvalidLayout)?;
457        if self.focused() == Some(id) && item.enabled {
458            style.ink = style.fill;
459            style.fill = style.focus;
460        }
461        ui.push_clip(self.bounds)?;
462        let result = ui.hud_button(id, rect, label, item.enabled, style);
463        ui.pop_clip();
464        result
465    }
466
467    /// Cancel mouse/touch capture and the pending activation, preserving focus
468    /// and offset. Call on consumer context changes even without another update.
469    pub fn cancel(&mut self) {
470        self.drag = None;
471        self.state.cancel_pointer();
472        self.active = None;
473    }
474
475    /// Reset offset, focus, content registration and input acceptance while
476    /// retaining allocated capacity and the once-per-host-frame input guard.
477    pub fn reset(&mut self) {
478        self.cancel();
479        self.scroll.reset();
480        self.items.clear();
481        self.state.begin_frame();
482        self.state.end_frame();
483        self.accepting = false;
484        self.shift = 0;
485    }
486
487    fn local_point(&self, raw: [f32; 2]) -> Option<[f32; 2]> {
488        let point = std::array::from_fn(|axis| {
489            ((raw[axis] as f64 - self.viewport.pixels().min[axis] as f64)
490                / self.viewport.scale() as f64) as f32
491        });
492        point.iter().all(|v| v.is_finite()).then_some(point)
493    }
494
495    fn content_point(&self, raw: [f32; 2]) -> [f32; 2] {
496        self.local_point(raw)
497            .and_then(|point| self.scroll.content_point(self.bounds, point))
498            .unwrap_or([f32::NAN; 2])
499    }
500
501    fn press(&mut self, pointer: Pointer, raw: [f32; 2]) {
502        if self.drag.is_some() {
503            return;
504        }
505        let Some(point) = self.local_point(raw).filter(|p| self.bounds.contains(*p)) else {
506            return;
507        };
508        self.state.pointer_down(self.content_point(raw));
509        self.drag = Some(Drag {
510            pointer,
511            start: point,
512            offset: self.scroll.offset(),
513            moved: false,
514        });
515    }
516
517    fn move_pointer(&mut self, pointer: Pointer, raw: [f32; 2]) {
518        let Some(mut drag) = self.drag.filter(|drag| drag.pointer == pointer) else {
519            return;
520        };
521        let Some(point) = self.local_point(raw) else {
522            self.cancel();
523            return;
524        };
525        let dx = point[0] as f64 - drag.start[0] as f64;
526        let dy = point[1] as f64 - drag.start[1] as f64;
527        if dx * dx + dy * dy >= 36. {
528            drag.moved = true;
529        }
530        if drag.moved {
531            self.state.cancel_pointer();
532            let offset =
533                (drag.offset as f64 - dy).clamp(0., self.scroll.max_offset() as f64) as f32;
534            let _ = self.scroll.set_offset(offset);
535        }
536        self.drag = Some(drag);
537    }
538
539    fn release(&mut self, pointer: Pointer, raw: [f32; 2]) {
540        if !self.drag.is_some_and(|drag| drag.pointer == pointer) {
541            return;
542        }
543        self.move_pointer(pointer, raw); // End may carry the only movement sample.
544        let Some(drag) = self.drag.take() else {
545            return;
546        };
547        if !drag.moved {
548            self.active = self
549                .state
550                .pointer_up(self.content_point(raw))
551                .or(self.active);
552        }
553    }
554}
555
556#[cfg(test)]
557mod tests {
558    use super::*;
559
560    const BOUNDS: UiRect = UiRect {
561        min: [20., 30.],
562        size: [100., 80.],
563    };
564    const ITEMS: [ScrollItem; 4] = [
565        ScrollItem {
566            id: 10,
567            rect: UiRect {
568                min: [0., 0.],
569                size: [100., 40.],
570            },
571            enabled: true,
572        },
573        ScrollItem {
574            id: 20,
575            rect: UiRect {
576                min: [0., 60.],
577                size: [100., 40.],
578            },
579            enabled: true,
580        },
581        ScrollItem {
582            id: 30,
583            rect: UiRect {
584                min: [0., 120.],
585                size: [100., 40.],
586            },
587            enabled: false,
588        },
589        ScrollItem {
590            id: 40,
591            rect: UiRect {
592                min: [0., 180.],
593                size: [100., 40.],
594            },
595            enabled: true,
596        },
597    ];
598
599    fn setup() -> ScrollRegion {
600        crate::edit(|s| *s = crate::State::default());
601        let mut region = ScrollRegion::new(4);
602        update(&mut region);
603        next();
604        region
605    }
606
607    fn viewport() -> Viewport {
608        Viewport::responsive([200.; 2], [0.; 4]).unwrap()
609    }
610
611    fn update(region: &mut ScrollRegion) {
612        region
613            .update(viewport(), BOUNDS, 220., &ITEMS, true)
614            .unwrap();
615    }
616
617    fn next() {
618        crate::edit(|s| {
619            s.frame += 1;
620            s.input.finish_frame();
621        });
622    }
623
624    fn key(code: u32) {
625        crate::key(code, true);
626        crate::key(code, false);
627    }
628
629    fn tap(x: f32, y: f32) {
630        crate::pointer(x, y, 0., 0.);
631        crate::button(1, true);
632        crate::button(1, false);
633    }
634
635    #[test]
636    fn navigation_reveals_offscreen_focus_before_confirmation_and_keeps_other_ui_focus() {
637        let mut region = setup();
638        let mut other = Ui::new();
639        other.begin(viewport());
640        other
641            .button(99, BOUNDS, "OTHER", true, ButtonStyle::default())
642            .unwrap();
643        key(0xff09);
644        other.finish(true);
645        assert_eq!(other.focused(), Some(99));
646        next();
647        for (id, offset) in [(10, 0.), (20, 20.), (40, 140.), (10, 0.)] {
648            key(0xff54);
649            update(&mut region);
650            assert_eq!(region.focused(), Some(id));
651            assert_eq!(region.scroll().offset(), offset);
652            assert!(!region.activated(id));
653            assert_eq!(other.focused(), Some(99));
654            next();
655        }
656        key(0xff52);
657        key(0xff0d);
658        update(&mut region);
659        assert_eq!(region.focused(), Some(40));
660        assert!(region.activated(40));
661        // Repeated processing of the same host frame never repeats activation.
662        update(&mut region);
663        assert!(!region.activated(40));
664    }
665
666    #[test]
667    fn clipped_children_and_half_open_edges_never_click_or_activate_unseen_focus() {
668        let mut region = setup();
669        tap(30., 125.); // Item 20's unscrolled bounds, below the viewport clip.
670        update(&mut region);
671        assert_eq!(region.focused(), None);
672        assert!(!region.activated(20));
673        next();
674        tap(30., 110.); // Bottom boundary is excluded.
675        update(&mut region);
676        assert!(!region.activated(20));
677        next();
678        tap(30., 100.); // Visible part of item 20.
679        update(&mut region);
680        assert!(region.activated(20));
681        region.scroll_by(f32::MAX).unwrap();
682        assert_eq!(region.focused(), Some(20));
683        assert_eq!(region.activate_focused(), None); // Reveal only.
684        assert_eq!(region.scroll().offset(), 60.);
685        assert_eq!(region.activate_focused(), Some(20));
686    }
687
688    #[test]
689    fn mouse_drag_moves_while_held_and_outside_without_releasing_a_button() {
690        let mut region = setup();
691        crate::pointer(30., 50., 0., 0.);
692        crate::button(1, true);
693        update(&mut region);
694        assert_eq!(region.focused(), Some(10));
695        next();
696        crate::pointer(30., 10., 0., -40.);
697        update(&mut region);
698        assert_eq!(region.scroll().offset(), 40.);
699        assert_eq!(region.state.captured(), None);
700        next();
701        crate::pointer(30., -30., 0., -40.);
702        update(&mut region);
703        assert_eq!(region.scroll().offset(), 80.);
704        next();
705        crate::pointer(30., 50., 0., 80.);
706        crate::button(1, false);
707        update(&mut region);
708        assert_eq!(region.scroll().offset(), 0.);
709        assert!(!region.activated(10));
710        assert!(region.drag.is_none());
711    }
712
713    #[test]
714    fn same_packet_movement_and_exhausted_drag_cancel_clicks() {
715        let mut region = setup();
716        crate::pointer(30., 50., 0., 0.);
717        crate::button(1, true);
718        crate::pointer(30., 60., 0., 10.); // Pull past top, then return.
719        crate::pointer(30., 50., 0., -10.);
720        crate::button(1, false);
721        update(&mut region);
722        assert_eq!(region.scroll().offset(), 0.);
723        assert!(!region.activated(10));
724        next();
725        crate::touch(1, 0, 30., 50.);
726        crate::touch(1, 2, 30., 40.); // End is the only motion sample.
727        update(&mut region);
728        assert_eq!(region.scroll().offset(), 10.);
729        assert!(!region.activated(10));
730    }
731
732    #[test]
733    fn touch_ownership_cancellation_and_quick_taps() {
734        let mut region = setup();
735        crate::touch(1, 0, 30., 50.);
736        crate::touch(2, 0, 30., 50.);
737        crate::touch(2, 1, 30., 5.);
738        crate::touch(2, 2, 30., 5.);
739        update(&mut region);
740        assert_eq!(region.scroll().offset(), 0.);
741        assert_eq!(region.state.captured(), Some(10));
742        next();
743        crate::touch(1, 1, 30., 20.);
744        crate::touch(1, 3, 30., 20.);
745        update(&mut region);
746        assert_eq!(region.scroll().offset(), 30.);
747        assert!(region.drag.is_none());
748        next();
749        crate::touch(1, 2, 30., 50.);
750        update(&mut region);
751        assert!(!region.activated(10));
752        region.scroll_by(-f32::MAX).unwrap();
753        next();
754        crate::touch(3, 0, 30., 50.);
755        crate::touch(3, 2, 30., 50.);
756        update(&mut region);
757        assert!(region.activated(10));
758    }
759
760    #[test]
761    fn focus_loss_disable_settings_and_overflow_cancel_pending_drags() {
762        for reason in 0..4 {
763            let mut region = setup();
764            crate::touch(1, 0, 30., 50.);
765            update(&mut region);
766            next();
767            crate::edit(|s| match reason {
768                0 => s.input.focus(false),
769                1 => {}
770                2 => s.controls_open = true,
771                _ => {
772                    s.input.overflow = true;
773                }
774            });
775            region
776                .update(viewport(), BOUNDS, 220., &ITEMS, reason != 1)
777                .unwrap();
778            assert!(region.drag.is_none());
779            assert_eq!(region.focused(), Some(10));
780            assert_eq!(region.activate_focused(), None);
781            next();
782            crate::edit(|s| {
783                s.input.focus(true);
784                s.controls_open = false;
785            });
786            crate::touch(1, 1, 30., 20.);
787            crate::touch(1, 2, 30., 50.);
788            update(&mut region);
789            assert_eq!(region.scroll().offset(), 0.);
790            assert!(!region.activated(10));
791        }
792    }
793
794    #[test]
795    fn resize_and_reorder_clamp_offset_without_retargeting_a_press() {
796        let mut region = setup();
797        region.scroll_by(f32::MAX).unwrap();
798        crate::touch(1, 0, 30., 85.); // Item 40 at scrolled Y=70..110.
799        update(&mut region);
800        assert_eq!(region.focused(), Some(40));
801        next();
802        crate::touch(1, 2, 30., 85.);
803        let bounds = UiRect {
804            size: [100., 160.],
805            ..BOUNDS
806        };
807        region
808            .update(viewport(), bounds, 220., &ITEMS, true)
809            .unwrap();
810        assert_eq!(region.scroll().offset(), 60.);
811        assert_eq!(region.focused(), Some(40));
812        assert!(!region.activated(40));
813        assert!(!region.activated(20));
814        next();
815        crate::touch(2, 0, 30., 40.); // Item 20.
816        region
817            .update(viewport(), bounds, 220., &ITEMS, true)
818            .unwrap();
819        next();
820        let mut changed = ITEMS;
821        changed.swap(0, 1);
822        crate::touch(2, 2, 30., 40.);
823        region
824            .update(viewport(), bounds, 220., &changed, true)
825            .unwrap();
826        assert!(!region.activated(20));
827        assert_eq!(region.focused(), Some(20));
828    }
829
830    #[test]
831    fn wheel_pages_exhaustion_and_input_frame_deduplication() {
832        let mut region = setup();
833        crate::pointer(130., 50., 0., 0.);
834        crate::wheel(-1.);
835        update(&mut region);
836        assert_eq!(region.scroll().offset(), 0.);
837        next();
838        crate::pointer(30., 50., 0., 0.);
839        crate::wheel(-1.);
840        update(&mut region);
841        assert_eq!(region.scroll().offset(), 40.);
842        update(&mut region);
843        assert_eq!(region.scroll().offset(), 40.);
844        next();
845        key(0xff56);
846        update(&mut region);
847        assert_eq!(region.scroll().offset(), 120.);
848        next();
849        key(0xff57);
850        update(&mut region);
851        assert_eq!(region.scroll().offset(), 140.);
852        assert!(!region.page(false));
853        next();
854        key(0xff55);
855        update(&mut region);
856        assert_eq!(region.scroll().offset(), 60.);
857        next();
858        key(0xff50);
859        update(&mut region);
860        assert_eq!(region.scroll().offset(), 0.);
861        assert!(!region.page(true));
862    }
863
864    #[test]
865    fn invalid_capacity_and_duplicate_updates_preserve_layout_but_cancel_capture() {
866        let mut region = setup();
867        crate::touch(1, 0, 30., 50.);
868        update(&mut region);
869        next();
870        let original = *region.scroll();
871        for (items, error) in [
872            (&[ITEMS[0]; 5][..], UiError::Capacity),
873            (&[ITEMS[0]; 2][..], UiError::DuplicateId),
874            (
875                &[ScrollItem {
876                    rect: UiRect {
877                        min: [0., 221.],
878                        size: [1.; 2],
879                    },
880                    ..ITEMS[0]
881                }][..],
882                UiError::InvalidLayout,
883            ),
884        ] {
885            assert_eq!(
886                region.update(viewport(), BOUNDS, 220., items, true),
887                Err(error)
888            );
889            assert_eq!(*region.scroll(), original);
890            assert_eq!(region.items, ITEMS);
891            assert_eq!(region.focused(), Some(10));
892            assert!(region.drag.is_none());
893            assert_eq!(region.activate_focused(), None);
894        }
895        assert_eq!(region.set_gamepad(4), Err(UiError::InvalidLayout));
896        crate::touch(1, 2, 30., 50.);
897        update(&mut region); // No failed packet replay on same-frame recovery.
898        assert!(!region.activated(10));
899        let capacity = region.capacity();
900        region.reset();
901        assert_eq!(region.capacity(), capacity);
902        assert_eq!(region.focused(), None);
903        assert_eq!(region.scroll().offset(), 0.);
904        assert!(region.items.is_empty());
905        let mut empty = ScrollRegion::new(0);
906        assert_eq!(
907            empty.update(viewport(), BOUNDS, 220., &ITEMS, true),
908            Err(UiError::Capacity)
909        );
910        empty.update(viewport(), BOUNDS, 220., &[], true).unwrap();
911        assert_eq!(empty.focus_next(false), None);
912    }
913
914    #[test]
915    fn scaled_safe_area_input_and_painted_vertices_share_the_clip() {
916        let mut region = setup();
917        let viewport = Viewport::fit([440., 420.], [200.; 2], [20., 10., 20., 10.]).unwrap();
918        assert_eq!(viewport.scale(), 2.);
919        crate::touch(1, 0, 80., 110.); // Local point [30,50].
920        crate::touch(1, 2, 80., 110.);
921        region.update(viewport, BOUNDS, 220., &ITEMS, true).unwrap();
922        assert!(region.activated(10));
923        let mut paint = Ui::new();
924        paint.begin(viewport);
925        for item in ITEMS {
926            region
927                .button(&mut paint, item.id, "ROW", ButtonStyle::default())
928                .unwrap();
929        }
930        crate::edit(|s| {
931            s.w = 440;
932            s.h = 420;
933            s.vertices.clear();
934        });
935        paint.paint();
936        crate::read(|s| {
937            assert!(!s.vertices.is_empty());
938            for vertex in &s.vertices {
939                let raw = [(vertex[0] + 1.) * 220., (1. - vertex[1]) * 210.];
940                let local = [(raw[0] - 20.) / 2., (raw[1] - 10.) / 2.];
941                for (axis, coordinate) in local.into_iter().enumerate() {
942                    assert!(coordinate >= BOUNDS.min[axis] - 0.001);
943                    assert!(coordinate <= BOUNDS.min[axis] + BOUNDS.size[axis] + 0.001);
944                }
945            }
946        });
947        // A full existing clip stack returns a capacity error without popping it.
948        for _ in 0..15 {
949            paint.push_clip(BOUNDS).unwrap();
950        }
951        assert_eq!(
952            region.button(&mut paint, 10, "ROW", ButtonStyle::default()),
953            Err(UiError::Capacity)
954        );
955        assert_eq!(paint.push_clip(BOUNDS), Err(UiError::Capacity));
956    }
957
958    #[test]
959    fn selected_gamepad_reconnect_suppression_and_remapped_methods() {
960        let mut region = setup();
961        region.set_gamepad(2).unwrap();
962        crate::edit(|s| {
963            s.input.pad_connected(2, true);
964            s.input.pad_button(2, 13, 1.);
965        });
966        update(&mut region);
967        assert_eq!(region.focused(), None); // Connection frame is suppressed.
968        next();
969        crate::edit(|s| {
970            s.input.pad_button(2, 13, 0.);
971            s.input.pad_button(2, 13, 1.);
972            s.input.pad_button(2, 0, 1.);
973        });
974        update(&mut region);
975        assert_eq!(region.focused(), Some(10));
976        assert!(region.activated(10));
977        // A caller's remapped edges use the same operations, no synthetic keys.
978        assert_eq!(region.focus_next(true), Some(40));
979        assert_eq!(region.activate_focused(), Some(40));
980        assert!(region.activated(40));
981    }
982}