Skip to main content

ftui_render/
frame.rs

1#![forbid(unsafe_code)]
2
3//! Frame = Buffer + metadata for a render pass.
4//!
5//! The `Frame` is the render target that `Model::view()` methods write to.
6//! It bundles the cell grid ([`Buffer`]) with metadata for cursor and
7//! mouse hit testing.
8//!
9//! # Design Rationale
10//!
11//! Frame does NOT own pools (GraphemePool, LinkRegistry) - those are passed
12//! separately or accessed via RenderContext to allow sharing across frames.
13//!
14//! # Usage
15//!
16//! ```
17//! use ftui_render::frame::Frame;
18//! use ftui_render::cell::Cell;
19//! use ftui_render::grapheme_pool::GraphemePool;
20//!
21//! let mut pool = GraphemePool::new();
22//! let mut frame = Frame::new(80, 24, &mut pool);
23//!
24//! // Draw content
25//! frame.buffer.set_raw(0, 0, Cell::from_char('H'));
26//! frame.buffer.set_raw(1, 0, Cell::from_char('i'));
27//!
28//! // Set cursor
29//! frame.set_cursor(Some((2, 0)));
30//! ```
31
32use crate::arena::FrameArena;
33use crate::budget::DegradationLevel;
34use crate::buffer::Buffer;
35use crate::cell::{Cell, CellContent, GraphemeId};
36use crate::drawing::{BorderChars, Draw};
37use crate::grapheme_pool::GraphemePool;
38use crate::{display_width, grapheme_width};
39use ftui_a11y::node::A11yNodeInfo;
40use ftui_a11y::tree::A11yTreeBuilder;
41use ftui_core::geometry::Rect;
42use unicode_segmentation::UnicodeSegmentation;
43
44/// Identifier for a clickable region in the hit grid.
45///
46/// Widgets register hit regions with unique IDs to enable mouse interaction.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
48pub struct HitId(pub u32);
49
50impl HitId {
51    /// Create a new hit ID from a raw value.
52    #[inline]
53    pub const fn new(id: u32) -> Self {
54        Self(id)
55    }
56
57    /// Get the raw ID value.
58    #[inline]
59    pub const fn id(self) -> u32 {
60        self.0
61    }
62}
63
64/// Opaque user data for hit callbacks.
65pub type HitData = u64;
66
67/// Optional ownership tag attached to a hit region.
68///
69/// Higher-level systems can use this to disambiguate layered hit regions
70/// without overloading `HitId` or `HitData`.
71pub type HitOwner = u64;
72
73/// Regions within a widget for mouse interaction.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
75pub enum HitRegion {
76    /// No interactive region.
77    #[default]
78    None,
79    /// Main content area.
80    Content,
81    /// Widget border area.
82    Border,
83    /// Scrollbar track or thumb.
84    Scrollbar,
85    /// Resize handle or drag target.
86    Handle,
87    /// Clickable button.
88    Button,
89    /// Hyperlink.
90    Link,
91    /// Custom region tag.
92    Custom(u8),
93}
94
95/// Full hit-test metadata, including optional ownership provenance.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub struct HitTestResult {
98    pub id: HitId,
99    pub region: HitRegion,
100    pub data: HitData,
101    pub owner: Option<HitOwner>,
102}
103
104impl HitTestResult {
105    #[inline]
106    pub const fn new(id: HitId, region: HitRegion, data: HitData, owner: Option<HitOwner>) -> Self {
107        Self {
108            id,
109            region,
110            data,
111            owner,
112        }
113    }
114
115    #[inline]
116    pub const fn into_tuple(self) -> (HitId, HitRegion, HitData) {
117        (self.id, self.region, self.data)
118    }
119}
120
121/// A single hit cell in the grid.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
123pub struct HitCell {
124    /// Widget that registered this cell, if any.
125    pub widget_id: Option<HitId>,
126    /// Region tag for the hit area.
127    pub region: HitRegion,
128    /// Extra data attached to this hit cell.
129    pub data: HitData,
130    /// Optional owner tag for higher-level hit routing.
131    pub owner: Option<HitOwner>,
132}
133
134impl HitCell {
135    /// Create a populated hit cell.
136    #[inline]
137    pub const fn new(widget_id: HitId, region: HitRegion, data: HitData) -> Self {
138        Self {
139            widget_id: Some(widget_id),
140            region,
141            data,
142            owner: None,
143        }
144    }
145
146    /// Create a populated hit cell with explicit owner provenance.
147    #[inline]
148    pub const fn new_with_owner(
149        widget_id: HitId,
150        region: HitRegion,
151        data: HitData,
152        owner: Option<HitOwner>,
153    ) -> Self {
154        Self {
155            widget_id: Some(widget_id),
156            region,
157            data,
158            owner,
159        }
160    }
161
162    /// Check if the cell is empty.
163    #[inline]
164    pub const fn is_empty(&self) -> bool {
165        self.widget_id.is_none()
166    }
167}
168
169/// Hit testing grid for mouse interaction.
170///
171/// Maps screen positions to widget IDs, enabling widgets to receive
172/// mouse events for their regions.
173#[derive(Debug, Clone)]
174pub struct HitGrid {
175    width: u16,
176    height: u16,
177    cells: Vec<HitCell>,
178}
179
180impl HitGrid {
181    /// Create a new hit grid with the given dimensions.
182    pub fn new(width: u16, height: u16) -> Self {
183        let size = width as usize * height as usize;
184        Self {
185            width,
186            height,
187            cells: vec![HitCell::default(); size],
188        }
189    }
190
191    /// Grid width.
192    #[inline]
193    pub const fn width(&self) -> u16 {
194        self.width
195    }
196
197    /// Grid height.
198    #[inline]
199    pub const fn height(&self) -> u16 {
200        self.height
201    }
202
203    /// Convert (x, y) to linear index.
204    #[inline]
205    fn index(&self, x: u16, y: u16) -> Option<usize> {
206        if x < self.width && y < self.height {
207            Some(y as usize * self.width as usize + x as usize)
208        } else {
209            None
210        }
211    }
212
213    /// Get the hit cell at (x, y).
214    #[inline]
215    #[must_use]
216    pub fn get(&self, x: u16, y: u16) -> Option<&HitCell> {
217        self.index(x, y).map(|i| &self.cells[i])
218    }
219
220    /// Get mutable reference to hit cell at (x, y).
221    #[inline]
222    #[must_use]
223    pub fn get_mut(&mut self, x: u16, y: u16) -> Option<&mut HitCell> {
224        self.index(x, y).map(|i| &mut self.cells[i])
225    }
226
227    /// Register a clickable region with the given hit metadata.
228    ///
229    /// All cells within the rectangle will map to this hit cell.
230    pub fn register(&mut self, rect: Rect, widget_id: HitId, region: HitRegion, data: HitData) {
231        self.register_with_owner(rect, widget_id, region, data, None);
232    }
233
234    /// Register a clickable region with the given hit metadata and owner.
235    pub fn register_with_owner(
236        &mut self,
237        rect: Rect,
238        widget_id: HitId,
239        region: HitRegion,
240        data: HitData,
241        owner: Option<HitOwner>,
242    ) {
243        // Use usize to avoid overflow for large coordinates
244        let x_end = (rect.x as usize + rect.width as usize).min(self.width as usize);
245        let y_end = (rect.y as usize + rect.height as usize).min(self.height as usize);
246
247        // Check if there's anything to do
248        if rect.x as usize >= x_end || rect.y as usize >= y_end {
249            return;
250        }
251
252        let hit_cell = HitCell::new_with_owner(widget_id, region, data, owner);
253
254        for y in rect.y as usize..y_end {
255            let row_start = y * self.width as usize;
256            let start = row_start + rect.x as usize;
257            let end = row_start + x_end;
258
259            // Optimize: use slice fill for contiguous memory access
260            self.cells[start..end].fill(hit_cell);
261        }
262    }
263
264    /// Hit test at the given position.
265    ///
266    /// Returns the hit tuple if a region is registered at (x, y).
267    #[must_use]
268    pub fn hit_test(&self, x: u16, y: u16) -> Option<(HitId, HitRegion, HitData)> {
269        self.hit_test_detailed(x, y).map(HitTestResult::into_tuple)
270    }
271
272    /// Hit test at the given position, preserving owner provenance.
273    #[must_use]
274    pub fn hit_test_detailed(&self, x: u16, y: u16) -> Option<HitTestResult> {
275        self.get(x, y).and_then(|cell| {
276            cell.widget_id
277                .map(|id| HitTestResult::new(id, cell.region, cell.data, cell.owner))
278        })
279    }
280
281    /// Return all hits within the given rectangle.
282    pub fn hits_in(&self, rect: Rect) -> Vec<(HitId, HitRegion, HitData)> {
283        let x_end = (rect.x as usize + rect.width as usize).min(self.width as usize) as u16;
284        let y_end = (rect.y as usize + rect.height as usize).min(self.height as usize) as u16;
285        let mut hits = Vec::new();
286
287        for y in rect.y..y_end {
288            for x in rect.x..x_end {
289                if let Some((id, region, data)) = self.hit_test(x, y) {
290                    hits.push((id, region, data));
291                }
292            }
293        }
294
295        hits
296    }
297
298    /// Clear all hit regions.
299    pub fn clear(&mut self) {
300        self.cells.fill(HitCell::default());
301    }
302}
303
304use crate::link_registry::LinkRegistry;
305
306/// Source of the cost estimate for widget scheduling.
307#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
308pub enum CostEstimateSource {
309    /// Measured from recent render timings.
310    Measured,
311    /// Derived from area-based fallback (cells * cost_per_cell).
312    AreaFallback,
313    /// Fixed default when no signals exist.
314    #[default]
315    FixedDefault,
316}
317
318/// Per-widget scheduling signals captured during rendering.
319///
320/// These signals are used by runtime policies (budgeted refresh, greedy
321/// selection) to prioritize which widgets to render when budget is tight.
322#[derive(Debug, Clone)]
323pub struct WidgetSignal {
324    /// Stable widget identifier.
325    pub widget_id: u64,
326    /// Whether this widget is essential.
327    pub essential: bool,
328    /// Base priority in [0, 1].
329    pub priority: f32,
330    /// Milliseconds since last render.
331    pub staleness_ms: u64,
332    /// Focus boost in [0, 1].
333    pub focus_boost: f32,
334    /// Interaction boost in [0, 1].
335    pub interaction_boost: f32,
336    /// Widget area in cells (width * height).
337    pub area_cells: u32,
338    /// Estimated render cost in microseconds.
339    pub cost_estimate_us: f32,
340    /// Recent measured cost (EMA), if available.
341    pub recent_cost_us: f32,
342    /// Cost estimate provenance.
343    pub estimate_source: CostEstimateSource,
344}
345
346impl Default for WidgetSignal {
347    fn default() -> Self {
348        Self {
349            widget_id: 0,
350            essential: false,
351            priority: 0.5,
352            staleness_ms: 0,
353            focus_boost: 0.0,
354            interaction_boost: 0.0,
355            area_cells: 1,
356            cost_estimate_us: 5.0,
357            recent_cost_us: 5.0,
358            estimate_source: CostEstimateSource::FixedDefault,
359        }
360    }
361}
362
363impl WidgetSignal {
364    /// Create a widget signal with neutral defaults.
365    #[must_use]
366    pub fn new(widget_id: u64) -> Self {
367        Self {
368            widget_id,
369            ..Self::default()
370        }
371    }
372}
373
374/// Value-of-Information remeasure request emitted by a virtualized widget during rendering.
375#[derive(Debug, Clone, Copy, PartialEq)]
376pub struct RemeasureRequest {
377    /// Stable widget identifier (or 0 when unset).
378    pub widget_id: u64,
379    /// Item index selected for remeasurement.
380    pub index: usize,
381    /// Value of Information (expected variance reduction) at decision time.
382    pub voi: f64,
383    /// Configured sample cost threshold.
384    pub cost: f64,
385    /// Posterior alpha parameter at decision time.
386    pub alpha: f64,
387    /// Posterior beta parameter at decision time.
388    pub beta: f64,
389}
390
391/// Widget render budget policy for a single frame.
392#[derive(Debug, Clone)]
393pub struct WidgetBudget {
394    allow_list: Option<Vec<u64>>,
395}
396
397impl Default for WidgetBudget {
398    fn default() -> Self {
399        Self::allow_all()
400    }
401}
402
403impl WidgetBudget {
404    /// Allow all widgets to render.
405    #[must_use]
406    pub fn allow_all() -> Self {
407        Self { allow_list: None }
408    }
409
410    /// Allow only a specific set of widget IDs.
411    #[must_use]
412    pub fn allow_only(mut ids: Vec<u64>) -> Self {
413        ids.sort_unstable();
414        ids.dedup();
415        Self {
416            allow_list: Some(ids),
417        }
418    }
419
420    /// Check whether a widget should be rendered.
421    #[inline]
422    pub fn allows(&self, widget_id: u64, essential: bool) -> bool {
423        if essential {
424            return true;
425        }
426        match &self.allow_list {
427            None => true,
428            Some(ids) => ids.binary_search(&widget_id).is_ok(),
429        }
430    }
431}
432
433/// Text flow direction for a frame or widget.
434#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
435pub enum TextDirection {
436    /// Left-to-right text flow.
437    #[default]
438    Ltr,
439    /// Right-to-left text flow.
440    Rtl,
441}
442
443impl TextDirection {
444    /// Whether this direction is left-to-right.
445    #[inline]
446    #[must_use]
447    pub const fn is_ltr(self) -> bool {
448        matches!(self, Self::Ltr)
449    }
450
451    /// Whether this direction is right-to-left.
452    #[inline]
453    #[must_use]
454    pub const fn is_rtl(self) -> bool {
455        matches!(self, Self::Rtl)
456    }
457}
458
459/// Frame = Buffer + metadata for a render pass.
460///
461/// The Frame is passed to `Model::view()` and contains everything needed
462/// to render a single frame. The Buffer holds cells; metadata controls
463/// cursor and enables mouse hit testing.
464///
465/// # Lifetime
466///
467/// The frame borrows the `GraphemePool` from the runtime, so it cannot outlive
468/// the render pass. This is correct because frames are ephemeral render targets.
469#[derive(Debug)]
470pub struct Frame<'a> {
471    /// The cell grid for this render pass.
472    pub buffer: Buffer,
473
474    /// Text flow direction for this frame (LTR or RTL).
475    pub text_direction: TextDirection,
476
477    /// Reference to the grapheme pool for interning strings.
478    pub pool: &'a mut GraphemePool,
479
480    /// Optional reference to link registry for hyperlinks.
481    pub links: Option<&'a mut LinkRegistry>,
482
483    /// Optional hit grid for mouse hit testing.
484    ///
485    /// When `Some`, widgets can register clickable regions.
486    pub hit_grid: Option<HitGrid>,
487
488    /// Optional ownership stack applied to registered hit regions.
489    hit_owner_stack: Vec<HitOwner>,
490
491    /// Widget render budget policy for this frame.
492    pub widget_budget: WidgetBudget,
493
494    /// Collected per-widget scheduling signals for this frame.
495    pub widget_signals: Vec<WidgetSignal>,
496
497    /// Collected VOI remeasure requests for this frame.
498    remeasure_requests: Vec<RemeasureRequest>,
499
500    /// Cursor position (if app wants to show cursor).
501    ///
502    /// Coordinates are relative to buffer (0-indexed).
503    pub cursor_position: Option<(u16, u16)>,
504
505    /// Whether cursor should be visible.
506    pub cursor_visible: bool,
507
508    /// Current degradation level from the render budget.
509    ///
510    /// Widgets can read this to skip expensive operations when the
511    /// budget is constrained (e.g., use ASCII borders instead of
512    /// Unicode, skip decorative rendering, etc.).
513    pub degradation: DegradationLevel,
514
515    /// Optional per-frame bump arena for temporary allocations.
516    ///
517    /// When set, widgets can use this arena for scratch allocations that
518    /// only live for the current frame (e.g., formatted strings, temporary
519    /// slices). The arena is reset at frame boundaries, eliminating
520    /// allocator churn on the hot render path.
521    pub arena: Option<&'a FrameArena>,
522
523    /// Accessibility tree builder for this frame, when the runtime collects
524    /// one (see [`Frame::push_a11y`]). `None` makes every a11y call a no-op.
525    pub a11y: Option<&'a mut A11yTreeBuilder>,
526
527    /// Container ids opened by [`Frame::with_a11y_scope`].
528    a11y_scope_stack: Vec<u64>,
529
530    /// Node ids in push (document) order.
531    a11y_order: Vec<u64>,
532
533    /// `(parent, child)` links to apply in [`Frame::finish_a11y`].
534    a11y_children: Vec<(u64, u64)>,
535
536    /// Node ids that were taken when pushed, mapped to the id the node got
537    /// instead (see [`Frame::push_a11y`]).
538    a11y_rekeyed: std::collections::HashMap<u64, u64>,
539
540    /// Explicit focus owner set via [`Frame::set_a11y_focused`] (e.g., from
541    /// `FocusManager::sync_to_frame`). `None` derives focus from pushed
542    /// `A11yState::focused` flags; `Some(target)` enforces `target` (or its
543    /// focused active descendant) as the unique focused node in the built tree.
544    a11y_explicit_focus: Option<Option<u64>>,
545}
546
547/// The next id to try for an accessibility node whose id is taken: the
548/// splitmix64 mix of `id`, a bijection, so repeated calls walk a sequence that
549/// does not return to `id` for any practical length.
550fn rekey_a11y_id(id: u64) -> u64 {
551    let mut z = id.wrapping_add(0x9E37_79B9_7F4A_7C15);
552    z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
553    z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
554    z ^ (z >> 31)
555}
556
557impl<'a> Frame<'a> {
558    /// Create a new frame with given dimensions and grapheme pool.
559    ///
560    /// The frame starts with no hit grid and visible cursor at no position.
561    pub fn new(width: u16, height: u16, pool: &'a mut GraphemePool) -> Self {
562        Self {
563            buffer: Buffer::new(width, height),
564            text_direction: TextDirection::default(),
565            pool,
566            links: None,
567            hit_grid: None,
568            hit_owner_stack: Vec::new(),
569            widget_budget: WidgetBudget::default(),
570            widget_signals: Vec::new(),
571            remeasure_requests: Vec::new(),
572            cursor_position: None,
573            cursor_visible: true,
574            degradation: DegradationLevel::Full,
575            arena: None,
576            a11y: None,
577            a11y_scope_stack: Vec::new(),
578            a11y_order: Vec::new(),
579            a11y_children: Vec::new(),
580            a11y_rekeyed: std::collections::HashMap::new(),
581            a11y_explicit_focus: None,
582        }
583    }
584
585    /// Create a frame from an existing buffer.
586    ///
587    /// This avoids per-frame buffer allocation when callers reuse buffers.
588    pub fn from_buffer(buffer: Buffer, pool: &'a mut GraphemePool) -> Self {
589        Self {
590            buffer,
591            text_direction: TextDirection::default(),
592            pool,
593            links: None,
594            hit_grid: None,
595            hit_owner_stack: Vec::new(),
596            widget_budget: WidgetBudget::default(),
597            widget_signals: Vec::new(),
598            remeasure_requests: Vec::new(),
599            cursor_position: None,
600            cursor_visible: true,
601            degradation: DegradationLevel::Full,
602            arena: None,
603            a11y: None,
604            a11y_scope_stack: Vec::new(),
605            a11y_order: Vec::new(),
606            a11y_children: Vec::new(),
607            a11y_rekeyed: std::collections::HashMap::new(),
608            a11y_explicit_focus: None,
609        }
610    }
611
612    /// Create a new frame with grapheme pool and link registry.
613    ///
614    /// This avoids double-borrowing issues when both pool and links
615    /// come from the same parent struct.
616    pub fn with_links(
617        width: u16,
618        height: u16,
619        pool: &'a mut GraphemePool,
620        links: &'a mut LinkRegistry,
621    ) -> Self {
622        Self {
623            buffer: Buffer::new(width, height),
624            text_direction: TextDirection::default(),
625            pool,
626            links: Some(links),
627            hit_grid: None,
628            hit_owner_stack: Vec::new(),
629            widget_budget: WidgetBudget::default(),
630            widget_signals: Vec::new(),
631            remeasure_requests: Vec::new(),
632            cursor_position: None,
633            cursor_visible: true,
634            degradation: DegradationLevel::Full,
635            arena: None,
636            a11y: None,
637            a11y_scope_stack: Vec::new(),
638            a11y_order: Vec::new(),
639            a11y_children: Vec::new(),
640            a11y_rekeyed: std::collections::HashMap::new(),
641            a11y_explicit_focus: None,
642        }
643    }
644
645    /// Set the text direction for this frame.
646    #[inline]
647    pub fn set_text_direction(&mut self, text_direction: TextDirection) {
648        self.text_direction = text_direction;
649    }
650
651    /// Create a frame with hit testing enabled.
652    ///
653    /// The hit grid allows widgets to register clickable regions.
654    pub fn with_hit_grid(width: u16, height: u16, pool: &'a mut GraphemePool) -> Self {
655        // Build the buffer first and size the grid from its (>=1-clamped)
656        // dimensions, so a degenerate 0 dimension cannot produce a drawable
657        // buffer paired with an empty grid that accepts registrations but
658        // never reports hits.
659        let buffer = Buffer::new(width, height);
660        let hit_grid = HitGrid::new(buffer.width(), buffer.height());
661        Self {
662            buffer,
663            pool,
664            links: None,
665            hit_grid: Some(hit_grid),
666            hit_owner_stack: Vec::new(),
667            widget_budget: WidgetBudget::default(),
668            widget_signals: Vec::new(),
669            remeasure_requests: Vec::new(),
670            cursor_position: None,
671            cursor_visible: true,
672            degradation: DegradationLevel::Full,
673            arena: None,
674            a11y: None,
675            a11y_scope_stack: Vec::new(),
676            a11y_order: Vec::new(),
677            a11y_children: Vec::new(),
678            a11y_rekeyed: std::collections::HashMap::new(),
679            a11y_explicit_focus: None,
680            text_direction: TextDirection::default(),
681        }
682    }
683
684    /// Set the link registry for this frame.
685    pub fn set_links(&mut self, links: &'a mut LinkRegistry) {
686        self.links = Some(links);
687    }
688
689    /// Set the per-frame bump arena for temporary allocations.
690    ///
691    /// Widgets can access the arena via [`arena()`](Self::arena) to
692    /// perform scratch allocations that only live for the current frame.
693    pub fn set_arena(&mut self, arena: &'a FrameArena) {
694        self.arena = Some(arena);
695    }
696
697    /// Returns the per-frame bump arena, if set.
698    ///
699    /// Widgets should use this for temporary allocations (formatted strings,
700    /// scratch slices) to avoid per-frame allocator churn.
701    pub fn arena(&self) -> Option<&'a FrameArena> {
702        self.arena
703    }
704
705    /// Register a hyperlink URL and return its ID.
706    ///
707    /// Returns 0 if link registry is not available or full.
708    pub fn register_link(&mut self, url: &str) -> u32 {
709        if let Some(ref mut links) = self.links {
710            links.register(url)
711        } else {
712            0
713        }
714    }
715
716    /// Set the widget render budget for this frame.
717    pub fn set_widget_budget(&mut self, budget: WidgetBudget) {
718        self.widget_budget = budget;
719    }
720
721    /// Check whether a widget should be rendered by widget ID, considering both degradation and widget budget.
722    #[inline]
723    pub fn should_render_widget_by_id(&self, widget_id: u64, essential: bool) -> bool {
724        self.should_render_widget(essential) && self.widget_budget.allows(widget_id, essential)
725    }
726
727    /// Check whether a budgeted widget should be rendered under the current widget budget and degradation.
728    #[inline]
729    pub fn should_render_budgeted_widget(&self, widget_id: u64, essential: bool) -> bool {
730        self.should_render_widget_by_id(widget_id, essential)
731    }
732
733    /// Register a widget scheduling signal for this frame.
734    pub fn register_widget_signal(&mut self, signal: WidgetSignal) {
735        self.widget_signals.push(signal);
736    }
737
738    /// Borrow the collected widget signals.
739    #[inline]
740    pub fn widget_signals(&self) -> &[WidgetSignal] {
741        &self.widget_signals
742    }
743
744    /// Take the collected widget signals, leaving an empty list.
745    #[inline]
746    pub fn take_widget_signals(&mut self) -> Vec<WidgetSignal> {
747        std::mem::take(&mut self.widget_signals)
748    }
749
750    /// Push a VOI remeasure request emitted during widget rendering.
751    pub fn push_remeasure_request(&mut self, req: RemeasureRequest) {
752        self.remeasure_requests.push(req);
753    }
754
755    /// Borrow the collected VOI remeasure requests.
756    #[inline]
757    pub fn remeasure_requests(&self) -> &[RemeasureRequest] {
758        &self.remeasure_requests
759    }
760
761    /// Take the collected VOI remeasure requests, leaving an empty list.
762    #[inline]
763    pub fn take_remeasure_requests(&mut self) -> Vec<RemeasureRequest> {
764        std::mem::take(&mut self.remeasure_requests)
765    }
766
767    /// Intern a string in the grapheme pool.
768    ///
769    /// Returns a `GraphemeId` that can be used to create a `Cell`.
770    /// The width is calculated automatically or can be provided if already known.
771    ///
772    /// # Panics
773    ///
774    /// Panics if width exceeds `GraphemeId::MAX_WIDTH`.
775    pub fn intern(&mut self, text: &str) -> GraphemeId {
776        let width = display_width(text).min(GraphemeId::MAX_WIDTH as usize) as u8;
777        self.pool.intern(text, width)
778    }
779
780    /// Intern a string with explicit width.
781    pub fn intern_with_width(&mut self, text: &str, width: u8) -> GraphemeId {
782        self.pool.intern(text, width)
783    }
784
785    /// Enable hit testing on an existing frame.
786    pub fn enable_hit_testing(&mut self) {
787        if self.hit_grid.is_none() {
788            self.hit_grid = Some(HitGrid::new(self.width(), self.height()));
789        }
790    }
791
792    /// Frame width in cells.
793    #[inline]
794    pub fn width(&self) -> u16 {
795        self.buffer.width()
796    }
797
798    /// Frame height in cells.
799    #[inline]
800    pub fn height(&self) -> u16 {
801        self.buffer.height()
802    }
803
804    /// Clear frame for next render.
805    ///
806    /// Resets both the buffer and hit grid (if present).
807    pub fn clear(&mut self) {
808        self.buffer.clear();
809        if let Some(ref mut grid) = self.hit_grid {
810            grid.clear();
811        }
812        self.cursor_position = None;
813        self.widget_signals.clear();
814        self.remeasure_requests.clear();
815    }
816
817    /// Set cursor position.
818    ///
819    /// Pass `None` to indicate no cursor should be shown at a specific position.
820    #[inline]
821    pub fn set_cursor(&mut self, position: Option<(u16, u16)>) {
822        self.cursor_position = position;
823    }
824
825    /// Set cursor visibility.
826    #[inline]
827    pub fn set_cursor_visible(&mut self, visible: bool) {
828        self.cursor_visible = visible;
829    }
830
831    /// Set the degradation level for this frame.
832    ///
833    /// Propagates to the buffer so widgets can read `buf.degradation`
834    /// during rendering without needing access to the full Frame.
835    #[inline]
836    pub fn set_degradation(&mut self, level: DegradationLevel) {
837        self.degradation = level;
838        self.buffer.degradation = level;
839    }
840
841    /// Whether a widget should be rendered under the current degradation level.
842    ///
843    /// Essential widgets render up through [`DegradationLevel::Skeleton`] (only
844    /// skipped at [`DegradationLevel::SkipFrame`]). Non-essential (decorative)
845    /// widgets are skipped at [`DegradationLevel::EssentialOnly`] and above.
846    #[inline]
847    pub fn should_render_widget(&self, essential: bool) -> bool {
848        self.degradation
849            .max(self.buffer.degradation)
850            .allows_widget(essential)
851    }
852
853    /// Get the bounding rectangle of the frame.
854    #[inline]
855    pub fn bounds(&self) -> Rect {
856        self.buffer.bounds()
857    }
858
859    /// The full drawable area of the frame (`(0, 0)` to `(width, height)`).
860    ///
861    /// Same as [`Frame::bounds`]; this is the name layout code reads best
862    /// (`Flex::horizontal().constraints(..).split(frame.area())`).
863    #[inline]
864    #[must_use]
865    pub fn area(&self) -> Rect {
866        self.buffer.bounds()
867    }
868
869    /// Register a hit region (if hit grid is enabled).
870    ///
871    /// Returns `true` if the region was registered, `false` if no hit grid.
872    ///
873    /// # Clipping
874    ///
875    /// The region is intersected with the current scissor stack of the
876    /// internal buffer. Parts of the region outside the scissor are
877    /// ignored.
878    pub fn register_hit(
879        &mut self,
880        rect: Rect,
881        id: HitId,
882        region: HitRegion,
883        data: HitData,
884    ) -> bool {
885        let owner = self.current_hit_owner();
886        if let Some(ref mut grid) = self.hit_grid {
887            // Clip against current scissor
888            let clipped = rect.intersection(&self.buffer.current_scissor());
889            if !clipped.is_empty() {
890                grid.register_with_owner(clipped, id, region, data, owner);
891            }
892            true
893        } else {
894            false
895        }
896    }
897
898    /// Temporarily attach ownership provenance to hit regions registered in `f`.
899    pub fn with_hit_owner<R>(&mut self, owner: HitOwner, f: impl FnOnce(&mut Self) -> R) -> R {
900        self.hit_owner_stack.push(owner);
901        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
902        self.hit_owner_stack.pop();
903        match result {
904            Ok(result) => result,
905            Err(payload) => std::panic::resume_unwind(payload),
906        }
907    }
908
909    // ── Accessibility tree collection ───────────────────────────────────
910
911    /// Whether an accessibility tree builder is attached to this frame.
912    #[must_use]
913    pub fn a11y_enabled(&self) -> bool {
914        self.a11y.is_some()
915    }
916
917    /// Attach the builder that collects this frame's accessibility nodes
918    /// (the runtime does this once per frame when accessibility is on).
919    pub fn set_a11y(&mut self, builder: &'a mut A11yTreeBuilder) {
920        self.a11y = Some(builder);
921    }
922
923    /// Push one accessibility node. A no-op without a builder.
924    ///
925    /// The node's parent defaults to the enclosing [`Frame::with_a11y_scope`]
926    /// container; a parent the widget set itself is kept. Ids must be stable
927    /// across frames so the tree can be diffed and changes announced: reuse
928    /// a hit id or widget id where one exists, otherwise
929    /// [`A11yNodeInfo::stable_id_for`].
930    ///
931    /// A node whose id another node already holds this frame gets a new id
932    /// derived from it. Sibling widgets at one rect share their default id,
933    /// and the builder replaces a node with the same id, so the first sibling
934    /// was dropped from the tree while its id stayed in the reading order.
935    /// The new id depends only on the taken one and the push order, so it is
936    /// the same in every frame that renders in the same order. A parent the
937    /// widget set to a re-keyed id follows the node it names.
938    pub fn push_a11y(&mut self, node: A11yNodeInfo) {
939        let _ = self.push_a11y_node(node);
940    }
941
942    /// [`Frame::push_a11y`], returning the id the node was stored under.
943    fn push_a11y_node(&mut self, mut node: A11yNodeInfo) -> Option<u64> {
944        let builder = self.a11y.as_deref_mut()?;
945        if let Some(parent) = node.parent
946            && let Some(&assigned) = self.a11y_rekeyed.get(&parent)
947        {
948            node.parent = Some(assigned);
949        }
950        if node.parent.is_none()
951            && let Some(&parent) = self.a11y_scope_stack.last()
952        {
953            node.parent = Some(parent);
954        }
955        if builder.node(node.id).is_some() {
956            let taken = node.id;
957            let mut id = taken;
958            while builder.node(id).is_some() {
959                id = rekey_a11y_id(id);
960            }
961            node.id = id;
962            self.a11y_rekeyed.insert(taken, id);
963        }
964        let id = node.id;
965        if let Some(parent) = node.parent {
966            self.a11y_children.push((parent, id));
967        }
968        self.a11y_order.push(id);
969        builder.add_node(node);
970        Some(id)
971    }
972
973    /// Push every node a widget reports
974    /// (`ftui_a11y::Accessible::accessibility_nodes`).
975    pub fn push_a11y_nodes(&mut self, nodes: impl IntoIterator<Item = A11yNodeInfo>) {
976        for node in nodes {
977            self.push_a11y(node);
978        }
979    }
980
981    /// Push `container` and make it the parent of every node pushed while
982    /// `f` runs (containers such as `Block` wrap their children with this).
983    /// Without a builder `f` simply runs.
984    pub fn with_a11y_scope<R>(
985        &mut self,
986        container: A11yNodeInfo,
987        f: impl FnOnce(&mut Self) -> R,
988    ) -> R {
989        let Some(id) = self.push_a11y_node(container) else {
990            return f(self);
991        };
992        self.a11y_scope_stack.push(id);
993        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
994        self.a11y_scope_stack.pop();
995        match result {
996            Ok(result) => result,
997            Err(payload) => std::panic::resume_unwind(payload),
998        }
999    }
1000
1001    /// Node ids in push (document) order.
1002    #[must_use]
1003    pub fn a11y_order(&self) -> &[u64] {
1004        &self.a11y_order
1005    }
1006
1007    /// Move the push order out (the runtime keeps it beside the built tree).
1008    pub fn take_a11y_order(&mut self) -> Vec<u64> {
1009        std::mem::take(&mut self.a11y_order)
1010    }
1011
1012    /// Declare the application's authoritative focus target for this frame
1013    /// (for example from `FocusManager::sync_to_frame`).
1014    ///
1015    /// When set, [`Frame::finish_a11y`] reconciles all pushed nodes so that at
1016    /// most one node in the built tree has `A11yState::focused = true` and the
1017    /// builder's focused ID matches it:
1018    /// - If `focused` resolves to a composite container whose subtree contains
1019    ///   a focused active descendant (e.g. a selected `ListItem`, `Tree` row,
1020    ///   or `Dialog` button), that descendant retains focus while any focused
1021    ///   flags outside the target subtree are cleared.
1022    /// - If `focused` resolves to a leaf or container with no focused child,
1023    ///   that node itself receives `state.focused = true`.
1024    /// - If `focused` is `None` (blurred or host unfocused) or absent from the
1025    ///   rendered frame, all `state.focused` flags are cleared and the tree
1026    ///   has no focused node.
1027    pub fn set_a11y_focused(&mut self, focused: Option<u64>) {
1028        self.a11y_explicit_focus = Some(focused);
1029    }
1030
1031    /// Apply the collected parent/child links to the builder and, when no
1032    /// root was set, make the first parentless node the root. Call once
1033    /// after the view has rendered and before the tree is built; a no-op
1034    /// without a builder.
1035    pub fn finish_a11y(&mut self) {
1036        let rekeyed = std::mem::take(&mut self.a11y_rekeyed);
1037        let explicit_focus = self.a11y_explicit_focus.take();
1038        let Some(builder) = self.a11y.as_deref_mut() else {
1039            return;
1040        };
1041        for (parent, child) in self.a11y_children.drain(..) {
1042            if let Some(node) = builder.node_mut(parent)
1043                && !node.children.contains(&child)
1044            {
1045                node.children.push(child);
1046            }
1047        }
1048        if builder.root().is_none()
1049            && let Some(&root) = self
1050                .a11y_order
1051                .iter()
1052                .find(|id| builder.node(**id).is_some_and(|node| node.parent.is_none()))
1053        {
1054            builder.set_root(root);
1055        }
1056        if let Some(target_opt) = explicit_focus {
1057            let resolved_target = target_opt.and_then(|target| {
1058                let mapped = rekeyed.get(&target).copied().unwrap_or(target);
1059                builder.node(mapped).map(|_| mapped)
1060            });
1061            let active_focus = resolved_target.map(|target| {
1062                let is_in_target_subtree = |builder: &A11yTreeBuilder, mut id: u64| -> bool {
1063                    let mut steps = 0usize;
1064                    loop {
1065                        if id == target {
1066                            return true;
1067                        }
1068                        let Some(parent) = builder.node(id).and_then(|n| n.parent) else {
1069                            return false;
1070                        };
1071                        id = parent;
1072                        steps += 1;
1073                        if steps > 256 {
1074                            return false;
1075                        }
1076                    }
1077                };
1078                self.a11y_order
1079                    .iter()
1080                    .copied()
1081                    .find(|&id| {
1082                        builder.node(id).is_some_and(|n| n.state.focused)
1083                            && is_in_target_subtree(builder, id)
1084                    })
1085                    .or_else(|| {
1086                        self.a11y_order.iter().copied().find(|&id| {
1087                            id != target
1088                                && builder.node(id).is_some_and(|n| n.state.selected)
1089                                && is_in_target_subtree(builder, id)
1090                        })
1091                    })
1092                    .unwrap_or(target)
1093            });
1094            for &id in &self.a11y_order {
1095                if let Some(node) = builder.node_mut(id) {
1096                    node.state.focused = Some(id) == active_focus;
1097                }
1098            }
1099            builder.set_focused(active_focus);
1100        } else if builder.focused().is_none()
1101            && let Some(&focused) = self
1102                .a11y_order
1103                .iter()
1104                .find(|id| builder.node(**id).is_some_and(|node| node.state.focused))
1105        {
1106            builder.set_focused(Some(focused));
1107        }
1108    }
1109
1110    /// Hit test at the given position (if hit grid is enabled).
1111    #[must_use]
1112    pub fn hit_test(&self, x: u16, y: u16) -> Option<(HitId, HitRegion, HitData)> {
1113        self.hit_grid.as_ref().and_then(|grid| grid.hit_test(x, y))
1114    }
1115
1116    /// Hit test at the given position, preserving owner provenance.
1117    #[must_use]
1118    pub fn hit_test_detailed(&self, x: u16, y: u16) -> Option<HitTestResult> {
1119        self.hit_grid
1120            .as_ref()
1121            .and_then(|grid| grid.hit_test_detailed(x, y))
1122    }
1123
1124    /// Register a hit region with default metadata (Content, data=0).
1125    pub fn register_hit_region(&mut self, rect: Rect, id: HitId) -> bool {
1126        self.register_hit(rect, id, HitRegion::Content, 0)
1127    }
1128
1129    #[inline]
1130    fn current_hit_owner(&self) -> Option<HitOwner> {
1131        self.hit_owner_stack.last().copied()
1132    }
1133}
1134
1135impl<'a> Draw for Frame<'a> {
1136    fn draw_horizontal_line(&mut self, x: u16, y: u16, width: u16, cell: Cell) {
1137        self.buffer.draw_horizontal_line(x, y, width, cell);
1138    }
1139
1140    fn draw_vertical_line(&mut self, x: u16, y: u16, height: u16, cell: Cell) {
1141        self.buffer.draw_vertical_line(x, y, height, cell);
1142    }
1143
1144    fn draw_rect_filled(&mut self, rect: Rect, cell: Cell) {
1145        self.buffer.draw_rect_filled(rect, cell);
1146    }
1147
1148    fn draw_rect_outline(&mut self, rect: Rect, cell: Cell) {
1149        self.buffer.draw_rect_outline(rect, cell);
1150    }
1151
1152    fn print_text(&mut self, x: u16, y: u16, text: &str, base_cell: Cell) -> u16 {
1153        self.print_text_clipped(x, y, text, base_cell, self.width())
1154    }
1155
1156    fn print_text_clipped(
1157        &mut self,
1158        x: u16,
1159        y: u16,
1160        text: &str,
1161        base_cell: Cell,
1162        max_x: u16,
1163    ) -> u16 {
1164        let mut cx = x;
1165        for grapheme in text.graphemes(true) {
1166            let width = grapheme_width(grapheme);
1167            if width == 0 {
1168                continue;
1169            }
1170
1171            if cx >= max_x {
1172                break;
1173            }
1174
1175            // Don't start a wide char if it won't fit
1176            if cx as u32 + width as u32 > max_x as u32 {
1177                break;
1178            }
1179
1180            // Intern grapheme if needed (unlike Buffer::print_text, we have the pool!)
1181            let content = if width > 1 || grapheme.chars().count() > 1 {
1182                let id = self.intern_with_width(grapheme, width as u8);
1183                CellContent::from_grapheme(id)
1184            } else if let Some(c) = grapheme.chars().next() {
1185                CellContent::from_char(c)
1186            } else {
1187                continue;
1188            };
1189
1190            let cell = Cell {
1191                content,
1192                fg: base_cell.fg,
1193                bg: base_cell.bg,
1194                attrs: base_cell.attrs,
1195            };
1196            self.buffer.set_fast(cx, y, cell);
1197
1198            cx = cx.saturating_add(width as u16);
1199        }
1200        cx
1201    }
1202
1203    fn draw_border(&mut self, rect: Rect, chars: BorderChars, base_cell: Cell) {
1204        self.buffer.draw_border(rect, chars, base_cell);
1205    }
1206
1207    fn draw_box(&mut self, rect: Rect, chars: BorderChars, border_cell: Cell, fill_cell: Cell) {
1208        self.buffer.draw_box(rect, chars, border_cell, fill_cell);
1209    }
1210
1211    fn paint_area(
1212        &mut self,
1213        rect: Rect,
1214        fg: Option<crate::cell::PackedRgba>,
1215        bg: Option<crate::cell::PackedRgba>,
1216    ) {
1217        self.buffer.paint_area(rect, fg, bg);
1218    }
1219}
1220
1221#[cfg(test)]
1222mod tests {
1223    use super::*;
1224    use crate::cell::Cell;
1225
1226    #[test]
1227    fn frame_creation() {
1228        let mut pool = GraphemePool::new();
1229        let frame = Frame::new(80, 24, &mut pool);
1230        assert_eq!(frame.width(), 80);
1231        assert_eq!(frame.height(), 24);
1232        assert!(frame.hit_grid.is_none());
1233        assert!(frame.cursor_position.is_none());
1234        assert!(frame.cursor_visible);
1235    }
1236
1237    #[test]
1238    fn frame_with_hit_grid() {
1239        let mut pool = GraphemePool::new();
1240        let frame = Frame::with_hit_grid(80, 24, &mut pool);
1241        assert!(frame.hit_grid.is_some());
1242        assert_eq!(frame.width(), 80);
1243        assert_eq!(frame.height(), 24);
1244    }
1245
1246    #[test]
1247    fn frame_cursor() {
1248        let mut pool = GraphemePool::new();
1249        let mut frame = Frame::new(80, 24, &mut pool);
1250        assert!(frame.cursor_position.is_none());
1251        assert!(frame.cursor_visible);
1252
1253        frame.set_cursor(Some((10, 5)));
1254        assert_eq!(frame.cursor_position, Some((10, 5)));
1255
1256        frame.set_cursor_visible(false);
1257        assert!(!frame.cursor_visible);
1258
1259        frame.set_cursor(None);
1260        assert!(frame.cursor_position.is_none());
1261    }
1262
1263    #[test]
1264    fn frame_clear() {
1265        let mut pool = GraphemePool::new();
1266        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);
1267
1268        // Add some content
1269        frame.buffer.set_raw(5, 5, Cell::from_char('X'));
1270        frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
1271
1272        // Verify content exists
1273        assert_eq!(frame.buffer.get(5, 5).unwrap().content.as_char(), Some('X'));
1274        assert_eq!(
1275            frame.hit_test(2, 2),
1276            Some((HitId::new(1), HitRegion::Content, 0))
1277        );
1278
1279        // Clear
1280        frame.clear();
1281
1282        // Verify cleared
1283        assert!(frame.buffer.get(5, 5).unwrap().is_empty());
1284        assert!(frame.hit_test(2, 2).is_none());
1285    }
1286
1287    #[test]
1288    fn frame_bounds() {
1289        let mut pool = GraphemePool::new();
1290        let frame = Frame::new(80, 24, &mut pool);
1291        let bounds = frame.bounds();
1292        assert_eq!(bounds.x, 0);
1293        assert_eq!(bounds.y, 0);
1294        assert_eq!(bounds.width, 80);
1295        assert_eq!(bounds.height, 24);
1296    }
1297
1298    // ── accessibility collection ───────────────────────────────────────
1299
1300    fn a11y_node(id: u64, role: ftui_a11y::node::A11yRole, name: &str) -> A11yNodeInfo {
1301        A11yNodeInfo::new(id, role, Rect::new(0, 0, 10, 1)).with_name(name)
1302    }
1303
1304    #[test]
1305    fn finish_a11y_derives_focus_from_node_state() {
1306        use ftui_a11y::node::{A11yNodeInfo, A11yRole, A11yState};
1307        use ftui_a11y::tree::A11yTreeBuilder;
1308
1309        let focused_state = A11yState {
1310            focused: true,
1311            ..A11yState::default()
1312        };
1313
1314        // No explicit focus: the first focused node in reading order wins.
1315        let mut pool = GraphemePool::new();
1316        let mut builder = A11yTreeBuilder::new();
1317        let mut frame = Frame::new(20, 4, &mut pool);
1318        frame.set_a11y(&mut builder);
1319        frame.push_a11y(A11yNodeInfo::new(
1320            1,
1321            A11yRole::Button,
1322            Rect::new(0, 0, 5, 1),
1323        ));
1324        frame.push_a11y(
1325            A11yNodeInfo::new(2, A11yRole::TextInput, Rect::new(0, 1, 5, 1))
1326                .with_state(focused_state.clone()),
1327        );
1328        frame.push_a11y(
1329            A11yNodeInfo::new(3, A11yRole::Button, Rect::new(0, 2, 5, 1))
1330                .with_state(focused_state.clone()),
1331        );
1332        frame.finish_a11y();
1333        drop(frame);
1334        assert_eq!(builder.focused(), Some(2));
1335
1336        // Explicit focus is left alone.
1337        let mut builder = A11yTreeBuilder::new();
1338        builder.set_focused(Some(9));
1339        let mut frame = Frame::new(20, 4, &mut pool);
1340        frame.set_a11y(&mut builder);
1341        frame.push_a11y(
1342            A11yNodeInfo::new(2, A11yRole::TextInput, Rect::new(0, 1, 5, 1))
1343                .with_state(focused_state),
1344        );
1345        frame.finish_a11y();
1346        drop(frame);
1347        assert_eq!(builder.focused(), Some(9));
1348
1349        // Nothing focused: stays unset.
1350        let mut builder = A11yTreeBuilder::new();
1351        let mut frame = Frame::new(20, 4, &mut pool);
1352        frame.set_a11y(&mut builder);
1353        frame.push_a11y(A11yNodeInfo::new(
1354            1,
1355            A11yRole::Button,
1356            Rect::new(0, 0, 5, 1),
1357        ));
1358        frame.finish_a11y();
1359        drop(frame);
1360        assert_eq!(builder.focused(), None);
1361    }
1362
1363    #[test]
1364    fn frame_a11y_is_a_noop_without_a_builder() {
1365        use ftui_a11y::node::A11yRole;
1366        let mut pool = GraphemePool::new();
1367        let mut frame = Frame::new(20, 5, &mut pool);
1368        assert!(!frame.a11y_enabled());
1369        frame.push_a11y(a11y_node(1, A11yRole::Label, "lonely"));
1370        let ran = frame.with_a11y_scope(a11y_node(2, A11yRole::Window, "w"), |f| {
1371            f.push_a11y(a11y_node(3, A11yRole::Button, "b"));
1372            42
1373        });
1374        assert_eq!(ran, 42);
1375        frame.finish_a11y();
1376        assert!(frame.a11y_order().is_empty());
1377        assert!(frame.take_a11y_order().is_empty());
1378    }
1379
1380    #[test]
1381    fn frame_a11y_collects_nodes_with_scope_parents_and_a_root() {
1382        use ftui_a11y::node::A11yRole;
1383        let mut pool = GraphemePool::new();
1384        let mut builder = A11yTreeBuilder::new();
1385        let mut frame = Frame::new(20, 5, &mut pool);
1386        frame.set_a11y(&mut builder);
1387        assert!(frame.a11y_enabled());
1388
1389        frame.with_a11y_scope(a11y_node(1, A11yRole::Window, "main"), |f| {
1390            f.push_a11y(a11y_node(2, A11yRole::Button, "ok"));
1391            f.with_a11y_scope(a11y_node(3, A11yRole::List, "items"), |f| {
1392                f.push_a11y_nodes(vec![
1393                    a11y_node(4, A11yRole::ListItem, "first"),
1394                    a11y_node(5, A11yRole::ListItem, "second"),
1395                ]);
1396            });
1397            // An explicit parent set by the widget is kept.
1398            f.push_a11y(a11y_node(6, A11yRole::Label, "detached").with_parent(99));
1399        });
1400        frame.push_a11y(a11y_node(7, A11yRole::Label, "status"));
1401        assert_eq!(frame.a11y_order(), &[1, 2, 3, 4, 5, 6, 7]);
1402        frame.finish_a11y();
1403        let order = frame.take_a11y_order();
1404        drop(frame);
1405
1406        let tree = builder.build();
1407        assert_eq!(tree.root_id(), Some(1), "first parentless node is the root");
1408        assert_eq!(tree.node(2).and_then(|n| n.parent), Some(1));
1409        assert_eq!(tree.node(4).and_then(|n| n.parent), Some(3));
1410        assert_eq!(tree.node(6).and_then(|n| n.parent), Some(99));
1411        assert_eq!(tree.node(7).and_then(|n| n.parent), None);
1412        // The explicit parent (99, never pushed) keeps node 6 out of the
1413        // scope container's children; the dangling link is simply dropped.
1414        assert_eq!(tree.node(1).map(|n| n.children.clone()), Some(vec![2, 3]));
1415        assert_eq!(tree.node(3).map(|n| n.children.clone()), Some(vec![4, 5]));
1416        assert_eq!(tree.ancestors(5), vec![5, 3, 1], "self, parent, root");
1417
1418        let text = tree.dump_text(&order);
1419        let lines: Vec<&str> = text.lines().collect();
1420        assert_eq!(lines.len(), 7, "{text}");
1421        assert!(
1422            lines[0].starts_with("Window \"main\" [] @0,0 10x1"),
1423            "{text}"
1424        );
1425        assert!(lines[1].starts_with("  Button \"ok\""), "{text}");
1426        assert!(lines[3].starts_with("    ListItem \"first\""), "{text}");
1427        assert!(lines[6].starts_with("Label \"status\""), "{text}");
1428    }
1429
1430    #[test]
1431    fn frame_a11y_rekeys_a_taken_id_instead_of_dropping_the_node() {
1432        use ftui_a11y::node::A11yRole;
1433
1434        // Two sibling containers at one rect share id 10; the second one's
1435        // children name it both through the scope and as an explicit parent.
1436        let render = |builder: &mut A11yTreeBuilder| {
1437            let mut pool = GraphemePool::new();
1438            let mut frame = Frame::new(20, 5, &mut pool);
1439            frame.set_a11y(builder);
1440            frame.with_a11y_scope(a11y_node(1, A11yRole::Window, "main"), |f| {
1441                f.with_a11y_scope(a11y_node(10, A11yRole::Group, "first"), |f| {
1442                    f.push_a11y(a11y_node(11, A11yRole::Label, "a"));
1443                });
1444                f.with_a11y_scope(a11y_node(10, A11yRole::Group, "second"), |f| {
1445                    f.push_a11y(a11y_node(11, A11yRole::Label, "b"));
1446                });
1447                f.push_a11y(a11y_node(12, A11yRole::Label, "c").with_parent(10));
1448            });
1449            frame.finish_a11y();
1450            frame.take_a11y_order()
1451        };
1452
1453        let mut builder = A11yTreeBuilder::new();
1454        let order = render(&mut builder);
1455        let tree = builder.build();
1456        assert_eq!(order.len(), 6);
1457        assert_eq!(tree.node_count(), 6, "no node was replaced");
1458        let unique: std::collections::HashSet<u64> = order.iter().copied().collect();
1459        assert_eq!(unique.len(), order.len(), "{order:?}");
1460
1461        let name = |id: u64| tree.node(id).and_then(|n| n.name.clone()).unwrap();
1462        let second = order[3];
1463        assert_eq!(name(order[1]), "first");
1464        assert_eq!(name(second), "second");
1465        assert_ne!(second, 10);
1466        // Each label sits under its own group, and the explicit parent 10,
1467        // pushed after the second group took 10's place, follows it.
1468        assert_eq!(tree.node(order[2]).and_then(|n| n.parent), Some(10));
1469        assert_eq!(tree.node(order[4]).and_then(|n| n.parent), Some(second));
1470        assert_eq!(tree.node(order[5]).and_then(|n| n.parent), Some(second));
1471        assert_eq!(name(order[4]), "b");
1472
1473        // The same render gives the same ids in the next frame.
1474        let mut again = A11yTreeBuilder::new();
1475        assert_eq!(render(&mut again), order);
1476    }
1477
1478    #[test]
1479    fn stable_a11y_ids_depend_on_role_and_bounds_only() {
1480        use ftui_a11y::node::A11yRole;
1481        let a = A11yNodeInfo::stable_id_for(A11yRole::Button, Rect::new(1, 2, 3, 4));
1482        let same = A11yNodeInfo::stable_id_for(A11yRole::Button, Rect::new(1, 2, 3, 4));
1483        let moved = A11yNodeInfo::stable_id_for(A11yRole::Button, Rect::new(2, 2, 3, 4));
1484        let other_role = A11yNodeInfo::stable_id_for(A11yRole::Label, Rect::new(1, 2, 3, 4));
1485        assert_eq!(a, same);
1486        assert_ne!(a, moved);
1487        assert_ne!(a, other_role);
1488    }
1489
1490    #[test]
1491    fn push_a11y_collects_nodes_in_render_order_with_block_nesting() {
1492        use ftui_a11y::node::A11yRole;
1493        use ftui_a11y::tree::A11yTreeBuilder;
1494
1495        let mut pool = GraphemePool::new();
1496        let mut builder = A11yTreeBuilder::new();
1497        let mut frame = Frame::new(40, 10, &mut pool);
1498        frame.set_a11y(&mut builder);
1499
1500        frame.with_a11y_scope(a11y_node(100, A11yRole::Group, "Form Block"), |f| {
1501            f.push_a11y(a11y_node(101, A11yRole::TextInput, "First"));
1502            f.push_a11y(a11y_node(102, A11yRole::TextInput, "Second"));
1503        });
1504        frame.finish_a11y();
1505        let order = frame.take_a11y_order();
1506        drop(frame);
1507
1508        let tree = builder.build();
1509        assert_eq!(order, vec![100, 101, 102]);
1510        assert_eq!(tree.node_count(), 3);
1511        assert_eq!(tree.root_id(), Some(100));
1512        assert_eq!(tree.node(101).and_then(|n| n.parent), Some(100));
1513        assert_eq!(tree.node(102).and_then(|n| n.parent), Some(100));
1514        assert_eq!(
1515            tree.node(100).map(|n| n.children.clone()),
1516            Some(vec![101, 102])
1517        );
1518    }
1519
1520    #[test]
1521    fn push_a11y_is_noop_without_builder() {
1522        frame_a11y_is_a_noop_without_a_builder();
1523    }
1524
1525    #[test]
1526    fn nested_scopes_three_deep_record_ancestry() {
1527        use ftui_a11y::node::A11yRole;
1528        use ftui_a11y::tree::A11yTreeBuilder;
1529
1530        let mut pool = GraphemePool::new();
1531        let mut builder = A11yTreeBuilder::new();
1532        let mut frame = Frame::new(40, 10, &mut pool);
1533        frame.set_a11y(&mut builder);
1534
1535        frame.with_a11y_scope(a11y_node(1, A11yRole::Window, "Win"), |f| {
1536            f.with_a11y_scope(a11y_node(2, A11yRole::Group, "Grp"), |f| {
1537                f.with_a11y_scope(a11y_node(3, A11yRole::List, "Lst"), |f| {
1538                    f.push_a11y(a11y_node(4, A11yRole::ListItem, "Itm"));
1539                });
1540            });
1541        });
1542        frame.finish_a11y();
1543        drop(frame);
1544
1545        let tree = builder.build();
1546        assert_eq!(tree.ancestors(4), vec![4, 3, 2, 1]);
1547    }
1548
1549    #[test]
1550    fn finish_a11y_applies_pending_children_once() {
1551        use ftui_a11y::node::A11yRole;
1552        use ftui_a11y::tree::A11yTreeBuilder;
1553
1554        let mut pool = GraphemePool::new();
1555        let mut builder = A11yTreeBuilder::new();
1556        let mut frame = Frame::new(40, 10, &mut pool);
1557        frame.set_a11y(&mut builder);
1558
1559        frame.with_a11y_scope(a11y_node(1, A11yRole::Group, "Parent"), |f| {
1560            f.push_a11y(a11y_node(2, A11yRole::Button, "Child"));
1561        });
1562        frame.finish_a11y();
1563        frame.finish_a11y();
1564        drop(frame);
1565
1566        let tree = builder.build();
1567        assert_eq!(tree.node(1).map(|n| n.children.clone()), Some(vec![2]));
1568    }
1569
1570    #[test]
1571    fn duplicate_ids_in_one_frame_debug_assert() {
1572        frame_a11y_rekeys_a_taken_id_instead_of_dropping_the_node();
1573    }
1574
1575    #[test]
1576    fn frame_area_is_the_full_buffer_rect() {
1577        let mut pool = GraphemePool::new();
1578        let frame = Frame::new(120, 40, &mut pool);
1579        assert_eq!(frame.area(), frame.bounds());
1580        assert_eq!(frame.area(), Rect::new(0, 0, 120, 40));
1581        // `Buffer::new` clamps to at least 1x1, so a "zero-sized" frame still
1582        // reports a well-formed, drawable area rather than an empty rect.
1583        let empty = Frame::new(0, 0, &mut pool);
1584        assert_eq!(empty.area(), empty.bounds());
1585        assert_eq!(empty.area(), Rect::new(0, 0, 1, 1));
1586    }
1587
1588    #[test]
1589    fn hit_grid_creation() {
1590        let grid = HitGrid::new(80, 24);
1591        assert_eq!(grid.width(), 80);
1592        assert_eq!(grid.height(), 24);
1593    }
1594
1595    #[test]
1596    fn hit_grid_registration() {
1597        let mut pool = GraphemePool::new();
1598        let mut frame = Frame::with_hit_grid(80, 24, &mut pool);
1599        let hit_id = HitId::new(42);
1600        let rect = Rect::new(10, 5, 20, 3);
1601
1602        frame.register_hit(rect, hit_id, HitRegion::Button, 99);
1603
1604        // Inside rect
1605        assert_eq!(frame.hit_test(15, 6), Some((hit_id, HitRegion::Button, 99)));
1606        assert_eq!(frame.hit_test(10, 5), Some((hit_id, HitRegion::Button, 99))); // Top-left corner
1607        assert_eq!(frame.hit_test(29, 7), Some((hit_id, HitRegion::Button, 99))); // Bottom-right corner
1608
1609        // Outside rect
1610        assert!(frame.hit_test(5, 5).is_none()); // Left of rect
1611        assert!(frame.hit_test(30, 6).is_none()); // Right of rect (exclusive)
1612        assert!(frame.hit_test(15, 8).is_none()); // Below rect
1613        assert!(frame.hit_test(15, 4).is_none()); // Above rect
1614    }
1615
1616    #[test]
1617    fn hit_grid_overlapping_regions() {
1618        let mut pool = GraphemePool::new();
1619        let mut frame = Frame::with_hit_grid(20, 20, &mut pool);
1620
1621        // Register two overlapping regions
1622        frame.register_hit(
1623            Rect::new(0, 0, 10, 10),
1624            HitId::new(1),
1625            HitRegion::Content,
1626            1,
1627        );
1628        frame.register_hit(Rect::new(5, 5, 10, 10), HitId::new(2), HitRegion::Border, 2);
1629
1630        // Non-overlapping region from first
1631        assert_eq!(
1632            frame.hit_test(2, 2),
1633            Some((HitId::new(1), HitRegion::Content, 1))
1634        );
1635
1636        // Overlapping region - second wins (last registered)
1637        assert_eq!(
1638            frame.hit_test(7, 7),
1639            Some((HitId::new(2), HitRegion::Border, 2))
1640        );
1641
1642        // Non-overlapping region from second
1643        assert_eq!(
1644            frame.hit_test(12, 12),
1645            Some((HitId::new(2), HitRegion::Border, 2))
1646        );
1647    }
1648
1649    #[test]
1650    fn hit_grid_out_of_bounds() {
1651        let mut pool = GraphemePool::new();
1652        let frame = Frame::with_hit_grid(10, 10, &mut pool);
1653
1654        // Out of bounds returns None
1655        assert!(frame.hit_test(100, 100).is_none());
1656        assert!(frame.hit_test(10, 0).is_none()); // Exclusive bound
1657        assert!(frame.hit_test(0, 10).is_none()); // Exclusive bound
1658    }
1659
1660    #[test]
1661    fn hit_id_properties() {
1662        let id = HitId::new(42);
1663        assert_eq!(id.id(), 42);
1664        assert_eq!(id, HitId(42));
1665    }
1666
1667    #[test]
1668    fn register_hit_region_no_grid() {
1669        let mut pool = GraphemePool::new();
1670        let mut frame = Frame::new(10, 10, &mut pool);
1671        let result = frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
1672        assert!(!result); // No hit grid, returns false
1673    }
1674
1675    #[test]
1676    fn register_hit_region_with_grid() {
1677        let mut pool = GraphemePool::new();
1678        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);
1679        let result = frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
1680        assert!(result); // Has hit grid, returns true
1681    }
1682
1683    #[test]
1684    fn hit_grid_clear() {
1685        let mut grid = HitGrid::new(10, 10);
1686        grid.register(Rect::new(0, 0, 5, 5), HitId::new(1), HitRegion::Content, 0);
1687
1688        assert_eq!(
1689            grid.hit_test(2, 2),
1690            Some((HitId::new(1), HitRegion::Content, 0))
1691        );
1692
1693        grid.clear();
1694
1695        assert!(grid.hit_test(2, 2).is_none());
1696    }
1697
1698    #[test]
1699    fn hit_grid_boundary_clipping() {
1700        let mut grid = HitGrid::new(10, 10);
1701
1702        // Register region that extends beyond grid
1703        grid.register(
1704            Rect::new(8, 8, 10, 10),
1705            HitId::new(1),
1706            HitRegion::Content,
1707            0,
1708        );
1709
1710        // Inside clipped region
1711        assert_eq!(
1712            grid.hit_test(9, 9),
1713            Some((HitId::new(1), HitRegion::Content, 0))
1714        );
1715
1716        // Outside grid
1717        assert!(grid.hit_test(10, 10).is_none());
1718    }
1719
1720    #[test]
1721    fn hit_grid_edge_and_corner_cells() {
1722        let mut grid = HitGrid::new(4, 4);
1723        grid.register(Rect::new(3, 0, 1, 4), HitId::new(7), HitRegion::Border, 11);
1724
1725        // Right-most column corners
1726        assert_eq!(
1727            grid.hit_test(3, 0),
1728            Some((HitId::new(7), HitRegion::Border, 11))
1729        );
1730        assert_eq!(
1731            grid.hit_test(3, 3),
1732            Some((HitId::new(7), HitRegion::Border, 11))
1733        );
1734
1735        // Neighboring cells remain empty
1736        assert!(grid.hit_test(2, 0).is_none());
1737        assert!(grid.hit_test(4, 0).is_none());
1738        assert!(grid.hit_test(3, 4).is_none());
1739
1740        let mut grid = HitGrid::new(4, 4);
1741        grid.register(Rect::new(0, 3, 4, 1), HitId::new(9), HitRegion::Content, 21);
1742
1743        // Bottom row corners
1744        assert_eq!(
1745            grid.hit_test(0, 3),
1746            Some((HitId::new(9), HitRegion::Content, 21))
1747        );
1748        assert_eq!(
1749            grid.hit_test(3, 3),
1750            Some((HitId::new(9), HitRegion::Content, 21))
1751        );
1752
1753        // Outside bottom row
1754        assert!(grid.hit_test(0, 2).is_none());
1755        assert!(grid.hit_test(0, 4).is_none());
1756    }
1757
1758    #[test]
1759    fn frame_register_hit_respects_nested_scissor() {
1760        let mut pool = GraphemePool::new();
1761        let mut frame = Frame::with_hit_grid(10, 10, &mut pool);
1762
1763        let outer = Rect::new(1, 1, 8, 8);
1764        frame.buffer.push_scissor(outer);
1765        assert_eq!(frame.buffer.current_scissor(), outer);
1766
1767        let inner = Rect::new(4, 4, 10, 10);
1768        frame.buffer.push_scissor(inner);
1769        let clipped = outer.intersection(&inner);
1770        let current = frame.buffer.current_scissor();
1771        assert_eq!(current, clipped);
1772
1773        // Monotonic intersection: inner scissor must stay within outer.
1774        assert!(outer.contains(current.x, current.y));
1775        assert!(outer.contains(
1776            current.right().saturating_sub(1),
1777            current.bottom().saturating_sub(1)
1778        ));
1779
1780        frame.register_hit(
1781            Rect::new(0, 0, 10, 10),
1782            HitId::new(3),
1783            HitRegion::Button,
1784            99,
1785        );
1786
1787        assert_eq!(
1788            frame.hit_test(4, 4),
1789            Some((HitId::new(3), HitRegion::Button, 99))
1790        );
1791        assert_eq!(
1792            frame.hit_test(8, 8),
1793            Some((HitId::new(3), HitRegion::Button, 99))
1794        );
1795        assert!(frame.hit_test(3, 3).is_none()); // inside outer, outside inner
1796        assert!(frame.hit_test(0, 0).is_none()); // outside all scissor
1797
1798        frame.buffer.pop_scissor();
1799        assert_eq!(frame.buffer.current_scissor(), outer);
1800    }
1801
1802    #[test]
1803    fn hit_grid_hits_in_area() {
1804        let mut grid = HitGrid::new(5, 5);
1805        grid.register(Rect::new(0, 0, 2, 2), HitId::new(1), HitRegion::Content, 10);
1806        grid.register(Rect::new(1, 1, 2, 2), HitId::new(2), HitRegion::Button, 20);
1807
1808        let hits = grid.hits_in(Rect::new(0, 0, 3, 3));
1809        assert!(hits.contains(&(HitId::new(1), HitRegion::Content, 10)));
1810        assert!(hits.contains(&(HitId::new(2), HitRegion::Button, 20)));
1811    }
1812
1813    #[test]
1814    fn frame_intern() {
1815        let mut pool = GraphemePool::new();
1816        let mut frame = Frame::new(10, 10, &mut pool);
1817
1818        let id = frame.intern("👋");
1819        assert_eq!(frame.pool.get(id), Some("👋"));
1820    }
1821
1822    #[test]
1823    fn frame_intern_with_width() {
1824        let mut pool = GraphemePool::new();
1825        let mut frame = Frame::new(10, 10, &mut pool);
1826
1827        let id = frame.intern_with_width("🧪", 2);
1828        assert_eq!(id.width(), 2);
1829        assert_eq!(frame.pool.get(id), Some("🧪"));
1830    }
1831
1832    #[test]
1833    fn frame_print_text_emoji_presentation_sets_continuation() {
1834        let mut pool = GraphemePool::new();
1835        let mut frame = Frame::new(5, 1, &mut pool);
1836
1837        // Use a skin-tone modifier sequence (width 2, multi-codepoint, no VS16
1838        // dependency) so the test is independent of ftui-core's VS16 policy.
1839        frame.print_text(0, 0, "👍🏽", Cell::from_char(' '));
1840
1841        let head = frame.buffer.get(0, 0).unwrap();
1842        let tail = frame.buffer.get(1, 0).unwrap();
1843
1844        assert_eq!(head.content.width(), 2);
1845        assert!(tail.content.is_continuation());
1846    }
1847
1848    #[test]
1849    fn frame_enable_hit_testing() {
1850        let mut pool = GraphemePool::new();
1851        let mut frame = Frame::new(10, 10, &mut pool);
1852        assert!(frame.hit_grid.is_none());
1853
1854        frame.enable_hit_testing();
1855        assert!(frame.hit_grid.is_some());
1856
1857        // Calling again is idempotent
1858        frame.enable_hit_testing();
1859        assert!(frame.hit_grid.is_some());
1860    }
1861
1862    #[test]
1863    fn frame_enable_hit_testing_then_register() {
1864        let mut pool = GraphemePool::new();
1865        let mut frame = Frame::new(10, 10, &mut pool);
1866        frame.enable_hit_testing();
1867
1868        let registered = frame.register_hit_region(Rect::new(0, 0, 5, 5), HitId::new(1));
1869        assert!(registered);
1870        assert_eq!(
1871            frame.hit_test(2, 2),
1872            Some((HitId::new(1), HitRegion::Content, 0))
1873        );
1874    }
1875
1876    #[test]
1877    fn hit_cell_default_is_empty() {
1878        let cell = HitCell::default();
1879        assert!(cell.is_empty());
1880        assert_eq!(cell.widget_id, None);
1881        assert_eq!(cell.region, HitRegion::None);
1882        assert_eq!(cell.data, 0);
1883    }
1884
1885    #[test]
1886    fn hit_cell_new_is_not_empty() {
1887        let cell = HitCell::new(HitId::new(1), HitRegion::Button, 42);
1888        assert!(!cell.is_empty());
1889        assert_eq!(cell.widget_id, Some(HitId::new(1)));
1890        assert_eq!(cell.region, HitRegion::Button);
1891        assert_eq!(cell.data, 42);
1892    }
1893
1894    #[test]
1895    fn hit_region_variants() {
1896        assert_eq!(HitRegion::default(), HitRegion::None);
1897
1898        // All variants are distinct
1899        let variants = [
1900            HitRegion::None,
1901            HitRegion::Content,
1902            HitRegion::Border,
1903            HitRegion::Scrollbar,
1904            HitRegion::Handle,
1905            HitRegion::Button,
1906            HitRegion::Link,
1907            HitRegion::Custom(0),
1908            HitRegion::Custom(1),
1909            HitRegion::Custom(255),
1910        ];
1911        for i in 0..variants.len() {
1912            for j in (i + 1)..variants.len() {
1913                assert_ne!(
1914                    variants[i], variants[j],
1915                    "variants {i} and {j} should differ"
1916                );
1917            }
1918        }
1919    }
1920
1921    #[test]
1922    fn hit_id_default() {
1923        let id = HitId::default();
1924        assert_eq!(id.id(), 0);
1925    }
1926
1927    #[test]
1928    fn hit_grid_initial_cells_empty() {
1929        let grid = HitGrid::new(5, 5);
1930        for y in 0..5 {
1931            for x in 0..5 {
1932                let cell = grid.get(x, y).unwrap();
1933                assert!(cell.is_empty());
1934            }
1935        }
1936    }
1937
1938    #[test]
1939    fn hit_grid_zero_dimensions() {
1940        let grid = HitGrid::new(0, 0);
1941        assert_eq!(grid.width(), 0);
1942        assert_eq!(grid.height(), 0);
1943        assert!(grid.get(0, 0).is_none());
1944        assert!(grid.hit_test(0, 0).is_none());
1945    }
1946
1947    #[test]
1948    fn hit_grid_hits_in_empty_area() {
1949        let grid = HitGrid::new(10, 10);
1950        let hits = grid.hits_in(Rect::new(0, 0, 5, 5));
1951        // All cells are empty, so no actual HitId hits
1952        assert!(hits.is_empty());
1953    }
1954
1955    #[test]
1956    fn hit_grid_hits_in_clipped_area() {
1957        let mut grid = HitGrid::new(5, 5);
1958        grid.register(Rect::new(0, 0, 5, 5), HitId::new(1), HitRegion::Content, 0);
1959
1960        // Query area extends beyond grid — should be clipped
1961        let hits = grid.hits_in(Rect::new(3, 3, 10, 10));
1962        assert_eq!(hits.len(), 4); // 2x2 cells inside grid
1963    }
1964
1965    #[test]
1966    fn hit_test_no_grid_returns_none() {
1967        let mut pool = GraphemePool::new();
1968        let frame = Frame::new(10, 10, &mut pool);
1969        assert!(frame.hit_test(0, 0).is_none());
1970    }
1971
1972    #[test]
1973    fn frame_cursor_operations() {
1974        let mut pool = GraphemePool::new();
1975        let mut frame = Frame::new(80, 24, &mut pool);
1976
1977        // Set position at edge of frame
1978        frame.set_cursor(Some((79, 23)));
1979        assert_eq!(frame.cursor_position, Some((79, 23)));
1980
1981        // Set position at origin
1982        frame.set_cursor(Some((0, 0)));
1983        assert_eq!(frame.cursor_position, Some((0, 0)));
1984
1985        // Toggle visibility
1986        frame.set_cursor_visible(false);
1987        assert!(!frame.cursor_visible);
1988        frame.set_cursor_visible(true);
1989        assert!(frame.cursor_visible);
1990    }
1991
1992    #[test]
1993    fn hit_data_large_values() {
1994        let mut grid = HitGrid::new(5, 5);
1995        // HitData is u64, test max value
1996        grid.register(
1997            Rect::new(0, 0, 1, 1),
1998            HitId::new(1),
1999            HitRegion::Content,
2000            u64::MAX,
2001        );
2002        let result = grid.hit_test(0, 0);
2003        assert_eq!(result, Some((HitId::new(1), HitRegion::Content, u64::MAX)));
2004    }
2005
2006    #[test]
2007    fn hit_id_large_value() {
2008        let id = HitId::new(u32::MAX);
2009        assert_eq!(id.id(), u32::MAX);
2010    }
2011
2012    #[test]
2013    fn frame_print_text_interns_complex_graphemes() {
2014        let mut pool = GraphemePool::new();
2015        let mut frame = Frame::new(10, 1, &mut pool);
2016
2017        // Flag emoji (complex grapheme)
2018        let flag = "🇺🇸";
2019        assert!(flag.chars().count() > 1);
2020
2021        frame.print_text(0, 0, flag, Cell::default());
2022
2023        let cell = frame.buffer.get(0, 0).unwrap();
2024        assert!(cell.content.is_grapheme());
2025
2026        let id = cell.content.grapheme_id().unwrap();
2027        assert_eq!(frame.pool.get(id), Some(flag));
2028    }
2029
2030    // --- HitId trait coverage ---
2031
2032    #[test]
2033    fn hit_id_debug_clone_copy_hash() {
2034        let id = HitId::new(99);
2035        let dbg = format!("{:?}", id);
2036        assert!(dbg.contains("99"), "Debug: {dbg}");
2037        let copied: HitId = id; // Copy
2038        assert_eq!(id, copied);
2039        // Hash: insert into set
2040        use std::collections::HashSet;
2041        let mut set = HashSet::new();
2042        set.insert(id);
2043        set.insert(HitId::new(99));
2044        assert_eq!(set.len(), 1);
2045        set.insert(HitId::new(100));
2046        assert_eq!(set.len(), 2);
2047    }
2048
2049    #[test]
2050    fn hit_id_eq_and_ne() {
2051        assert_eq!(HitId::new(0), HitId::new(0));
2052        assert_ne!(HitId::new(0), HitId::new(1));
2053        assert_ne!(HitId::new(u32::MAX), HitId::default());
2054    }
2055
2056    // --- HitRegion trait coverage ---
2057
2058    #[test]
2059    fn hit_region_debug_clone_copy_hash() {
2060        let r = HitRegion::Custom(42);
2061        let dbg = format!("{:?}", r);
2062        assert!(dbg.contains("Custom"), "Debug: {dbg}");
2063        let copied: HitRegion = r; // Copy
2064        assert_eq!(r, copied);
2065        use std::collections::HashSet;
2066        let mut set = HashSet::new();
2067        set.insert(r);
2068        set.insert(HitRegion::Custom(42));
2069        assert_eq!(set.len(), 1);
2070    }
2071
2072    // --- HitCell trait coverage ---
2073
2074    #[test]
2075    fn hit_cell_debug_clone_copy_eq() {
2076        let cell = HitCell::new(HitId::new(5), HitRegion::Link, 123);
2077        let dbg = format!("{:?}", cell);
2078        assert!(dbg.contains("Link"), "Debug: {dbg}");
2079        let copied: HitCell = cell; // Copy
2080        assert_eq!(cell, copied);
2081        // ne
2082        assert_ne!(cell, HitCell::default());
2083    }
2084
2085    // --- HitGrid edge cases ---
2086
2087    #[test]
2088    fn hit_grid_clone() {
2089        let mut grid = HitGrid::new(5, 5);
2090        grid.register(Rect::new(0, 0, 2, 2), HitId::new(1), HitRegion::Content, 7);
2091        let clone = grid.clone();
2092        assert_eq!(clone.width(), 5);
2093        assert_eq!(
2094            clone.hit_test(0, 0),
2095            Some((HitId::new(1), HitRegion::Content, 7))
2096        );
2097    }
2098
2099    #[test]
2100    fn hit_grid_get_mut() {
2101        let mut grid = HitGrid::new(5, 5);
2102        // Mutate a cell directly
2103        if let Some(cell) = grid.get_mut(2, 3) {
2104            *cell = HitCell::new(HitId::new(77), HitRegion::Handle, 55);
2105        }
2106        assert_eq!(
2107            grid.hit_test(2, 3),
2108            Some((HitId::new(77), HitRegion::Handle, 55))
2109        );
2110        // Out of bounds returns None
2111        assert!(grid.get_mut(5, 5).is_none());
2112    }
2113
2114    #[test]
2115    fn hit_grid_zero_width_nonzero_height() {
2116        let grid = HitGrid::new(0, 10);
2117        assert_eq!(grid.width(), 0);
2118        assert_eq!(grid.height(), 10);
2119        assert!(grid.get(0, 0).is_none());
2120        assert!(grid.hit_test(0, 5).is_none());
2121    }
2122
2123    #[test]
2124    fn hit_grid_nonzero_width_zero_height() {
2125        let grid = HitGrid::new(10, 0);
2126        assert_eq!(grid.width(), 10);
2127        assert_eq!(grid.height(), 0);
2128        assert!(grid.get(0, 0).is_none());
2129    }
2130
2131    #[test]
2132    fn hit_grid_register_zero_width_rect() {
2133        let mut grid = HitGrid::new(10, 10);
2134        grid.register(Rect::new(2, 2, 0, 5), HitId::new(1), HitRegion::Content, 0);
2135        // Nothing should be registered
2136        assert!(grid.hit_test(2, 2).is_none());
2137    }
2138
2139    #[test]
2140    fn hit_grid_register_zero_height_rect() {
2141        let mut grid = HitGrid::new(10, 10);
2142        grid.register(Rect::new(2, 2, 5, 0), HitId::new(1), HitRegion::Content, 0);
2143        assert!(grid.hit_test(2, 2).is_none());
2144    }
2145
2146    #[test]
2147    fn hit_grid_register_past_bounds() {
2148        let mut grid = HitGrid::new(10, 10);
2149        // Rect starts past the grid boundary
2150        grid.register(
2151            Rect::new(10, 10, 5, 5),
2152            HitId::new(1),
2153            HitRegion::Content,
2154            0,
2155        );
2156        assert!(grid.hit_test(9, 9).is_none());
2157    }
2158
2159    #[test]
2160    fn hit_grid_full_coverage() {
2161        let mut grid = HitGrid::new(3, 3);
2162        grid.register(Rect::new(0, 0, 3, 3), HitId::new(1), HitRegion::Content, 0);
2163        // Every cell should be filled
2164        for y in 0..3 {
2165            for x in 0..3 {
2166                assert_eq!(
2167                    grid.hit_test(x, y),
2168                    Some((HitId::new(1), HitRegion::Content, 0))
2169                );
2170            }
2171        }
2172    }
2173
2174    #[test]
2175    fn hit_grid_single_cell() {
2176        let mut grid = HitGrid::new(1, 1);
2177        grid.register(Rect::new(0, 0, 1, 1), HitId::new(1), HitRegion::Button, 42);
2178        assert_eq!(
2179            grid.hit_test(0, 0),
2180            Some((HitId::new(1), HitRegion::Button, 42))
2181        );
2182        assert!(grid.hit_test(1, 0).is_none());
2183        assert!(grid.hit_test(0, 1).is_none());
2184    }
2185
2186    #[test]
2187    fn hit_grid_hits_in_outside_rect() {
2188        let mut grid = HitGrid::new(5, 5);
2189        grid.register(Rect::new(0, 0, 2, 2), HitId::new(1), HitRegion::Content, 0);
2190        // Query area completely outside registered region
2191        let hits = grid.hits_in(Rect::new(3, 3, 2, 2));
2192        assert!(hits.is_empty());
2193    }
2194
2195    #[test]
2196    fn hit_grid_hits_in_zero_rect() {
2197        let mut grid = HitGrid::new(5, 5);
2198        grid.register(Rect::new(0, 0, 5, 5), HitId::new(1), HitRegion::Content, 0);
2199        let hits = grid.hits_in(Rect::new(2, 2, 0, 0));
2200        assert!(hits.is_empty());
2201    }
2202
2203    // --- CostEstimateSource ---
2204
2205    #[test]
2206    fn cost_estimate_source_traits() {
2207        let a = CostEstimateSource::Measured;
2208        let b = CostEstimateSource::AreaFallback;
2209        let c = CostEstimateSource::FixedDefault;
2210        let dbg = format!("{:?}", a);
2211        assert!(dbg.contains("Measured"), "Debug: {dbg}");
2212
2213        // Default
2214        assert_eq!(
2215            CostEstimateSource::default(),
2216            CostEstimateSource::FixedDefault
2217        );
2218
2219        // Clone/Copy
2220        let copied: CostEstimateSource = a;
2221        assert_eq!(a, copied);
2222
2223        // All variants distinct
2224        assert_ne!(a, b);
2225        assert_ne!(b, c);
2226        assert_ne!(a, c);
2227    }
2228
2229    // --- WidgetSignal ---
2230
2231    #[test]
2232    fn widget_signal_default() {
2233        let sig = WidgetSignal::default();
2234        assert_eq!(sig.widget_id, 0);
2235        assert!(!sig.essential);
2236        assert!((sig.priority - 0.5).abs() < f32::EPSILON);
2237        assert_eq!(sig.staleness_ms, 0);
2238        assert!((sig.focus_boost - 0.0).abs() < f32::EPSILON);
2239        assert!((sig.interaction_boost - 0.0).abs() < f32::EPSILON);
2240        assert_eq!(sig.area_cells, 1);
2241        assert!((sig.cost_estimate_us - 5.0).abs() < f32::EPSILON);
2242        assert!((sig.recent_cost_us - 5.0).abs() < f32::EPSILON);
2243        assert_eq!(sig.estimate_source, CostEstimateSource::FixedDefault);
2244    }
2245
2246    #[test]
2247    fn widget_signal_new() {
2248        let sig = WidgetSignal::new(42);
2249        assert_eq!(sig.widget_id, 42);
2250        // Other fields should be default
2251        assert!(!sig.essential);
2252        assert!((sig.priority - 0.5).abs() < f32::EPSILON);
2253    }
2254
2255    #[test]
2256    fn widget_signal_debug_clone() {
2257        let sig = WidgetSignal::new(7);
2258        let dbg = format!("{:?}", sig);
2259        assert!(dbg.contains("widget_id"), "Debug: {dbg}");
2260        let cloned = sig.clone();
2261        assert_eq!(cloned.widget_id, 7);
2262    }
2263
2264    // --- WidgetBudget ---
2265
2266    #[test]
2267    fn widget_budget_default_is_allow_all() {
2268        let budget = WidgetBudget::default();
2269        assert!(budget.allows(0, false));
2270        assert!(budget.allows(u64::MAX, false));
2271        assert!(budget.allows(42, true));
2272    }
2273
2274    #[test]
2275    fn widget_budget_allow_only() {
2276        let budget = WidgetBudget::allow_only(vec![10, 20, 30]);
2277        assert!(budget.allows(10, false));
2278        assert!(budget.allows(20, false));
2279        assert!(budget.allows(30, false));
2280        assert!(!budget.allows(15, false));
2281        assert!(!budget.allows(0, false));
2282    }
2283
2284    #[test]
2285    fn widget_budget_essential_always_allowed() {
2286        let budget = WidgetBudget::allow_only(vec![10]);
2287        // Essential widgets bypass the allow list
2288        assert!(budget.allows(999, true));
2289        assert!(budget.allows(0, true));
2290    }
2291
2292    #[test]
2293    fn widget_budget_allow_only_dedup() {
2294        let budget = WidgetBudget::allow_only(vec![5, 5, 5, 10, 10]);
2295        assert!(budget.allows(5, false));
2296        assert!(budget.allows(10, false));
2297        assert!(!budget.allows(7, false));
2298    }
2299
2300    #[test]
2301    fn widget_budget_allow_only_empty() {
2302        let budget = WidgetBudget::allow_only(vec![]);
2303        // No widgets allowed (except essential)
2304        assert!(!budget.allows(0, false));
2305        assert!(!budget.allows(1, false));
2306        assert!(budget.allows(1, true)); // essential always passes
2307    }
2308
2309    #[test]
2310    fn widget_budget_debug_clone() {
2311        let budget = WidgetBudget::allow_only(vec![1, 2, 3]);
2312        let dbg = format!("{:?}", budget);
2313        assert!(dbg.contains("allow_list"), "Debug: {dbg}");
2314        let cloned = budget.clone();
2315        assert!(cloned.allows(2, false));
2316    }
2317
2318    // --- Frame construction variants ---
2319
2320    #[test]
2321    fn frame_zero_dimensions_clamped_to_one() {
2322        let mut pool = GraphemePool::new();
2323        let frame = Frame::new(0, 0, &mut pool);
2324        assert_eq!(frame.buffer.width(), 1);
2325        assert_eq!(frame.buffer.height(), 1);
2326    }
2327
2328    #[test]
2329    fn frame_from_buffer() {
2330        let mut pool = GraphemePool::new();
2331        let mut buf = Buffer::new(20, 10);
2332        buf.set_raw(5, 5, Cell::from_char('Z'));
2333        let frame = Frame::from_buffer(buf, &mut pool);
2334        assert_eq!(frame.width(), 20);
2335        assert_eq!(frame.height(), 10);
2336        assert_eq!(frame.buffer.get(5, 5).unwrap().content.as_char(), Some('Z'));
2337        assert!(frame.hit_grid.is_none());
2338        assert!(frame.cursor_visible);
2339    }
2340
2341    #[test]
2342    fn frame_with_links() {
2343        let mut pool = GraphemePool::new();
2344        let mut links = LinkRegistry::new();
2345        let frame = Frame::with_links(10, 5, &mut pool, &mut links);
2346        assert!(frame.links.is_some());
2347        assert_eq!(frame.width(), 10);
2348        assert_eq!(frame.height(), 5);
2349    }
2350
2351    #[test]
2352    fn frame_set_links() {
2353        let mut pool = GraphemePool::new();
2354        let mut links = LinkRegistry::new();
2355        let mut frame = Frame::new(10, 5, &mut pool);
2356        assert!(frame.links.is_none());
2357        frame.set_links(&mut links);
2358        assert!(frame.links.is_some());
2359    }
2360
2361    #[test]
2362    fn frame_register_link_no_registry() {
2363        let mut pool = GraphemePool::new();
2364        let mut frame = Frame::new(10, 5, &mut pool);
2365        // No link registry => returns 0
2366        let id = frame.register_link("https://example.com");
2367        assert_eq!(id, 0);
2368    }
2369
2370    #[test]
2371    fn frame_register_link_with_registry() {
2372        let mut pool = GraphemePool::new();
2373        let mut links = LinkRegistry::new();
2374        let mut frame = Frame::with_links(10, 5, &mut pool, &mut links);
2375        let id = frame.register_link("https://example.com");
2376        assert!(id > 0);
2377        // Same URL should return same ID
2378        let id2 = frame.register_link("https://example.com");
2379        assert_eq!(id, id2);
2380        // Different URL should return different ID
2381        let id3 = frame.register_link("https://other.com");
2382        assert_ne!(id, id3);
2383    }
2384
2385    // --- Frame widget budget integration ---
2386
2387    #[test]
2388    fn frame_set_widget_budget() {
2389        let mut pool = GraphemePool::new();
2390        let mut frame = Frame::new(10, 10, &mut pool);
2391
2392        // Default allows all
2393        assert!(frame.should_render_widget_by_id(42, false));
2394
2395        // Set restricted budget
2396        frame.set_widget_budget(WidgetBudget::allow_only(vec![1, 2]));
2397        assert!(frame.should_render_widget_by_id(1, false));
2398        assert!(!frame.should_render_widget_by_id(42, false));
2399        assert!(frame.should_render_widget_by_id(42, true)); // essential
2400    }
2401
2402    // --- Frame widget signals ---
2403
2404    #[test]
2405    fn frame_widget_signals_lifecycle() {
2406        let mut pool = GraphemePool::new();
2407        let mut frame = Frame::new(10, 10, &mut pool);
2408        assert!(frame.widget_signals().is_empty());
2409
2410        frame.register_widget_signal(WidgetSignal::new(1));
2411        frame.register_widget_signal(WidgetSignal::new(2));
2412        assert_eq!(frame.widget_signals().len(), 2);
2413        assert_eq!(frame.widget_signals()[0].widget_id, 1);
2414        assert_eq!(frame.widget_signals()[1].widget_id, 2);
2415
2416        let taken = frame.take_widget_signals();
2417        assert_eq!(taken.len(), 2);
2418        assert!(frame.widget_signals().is_empty());
2419    }
2420
2421    #[test]
2422    fn frame_clear_resets_signals_and_cursor() {
2423        let mut pool = GraphemePool::new();
2424        let mut frame = Frame::new(10, 10, &mut pool);
2425        frame.set_cursor(Some((5, 5)));
2426        frame.register_widget_signal(WidgetSignal::new(1));
2427        assert!(frame.cursor_position.is_some());
2428        assert!(!frame.widget_signals().is_empty());
2429
2430        frame.clear();
2431        assert!(frame.cursor_position.is_none());
2432        assert!(frame.widget_signals().is_empty());
2433    }
2434
2435    // --- Frame degradation ---
2436
2437    #[test]
2438    fn frame_set_degradation_propagates_to_buffer() {
2439        let mut pool = GraphemePool::new();
2440        let mut frame = Frame::new(10, 10, &mut pool);
2441        assert_eq!(frame.degradation, DegradationLevel::Full);
2442        assert_eq!(frame.buffer.degradation, DegradationLevel::Full);
2443
2444        frame.set_degradation(DegradationLevel::SimpleBorders);
2445        assert_eq!(frame.degradation, DegradationLevel::SimpleBorders);
2446        assert_eq!(frame.buffer.degradation, DegradationLevel::SimpleBorders);
2447
2448        frame.set_degradation(DegradationLevel::EssentialOnly);
2449        assert_eq!(frame.degradation, DegradationLevel::EssentialOnly);
2450        assert_eq!(frame.buffer.degradation, DegradationLevel::EssentialOnly);
2451    }
2452
2453    #[test]
2454    fn frame_should_render_widget() {
2455        let mut pool = GraphemePool::new();
2456        let mut frame = Frame::new(10, 10, &mut pool);
2457
2458        // Full: all widgets allowed
2459        assert!(frame.should_render_widget(true));
2460        assert!(frame.should_render_widget(false));
2461
2462        // SimpleBorders & NoStyling: all widgets allowed
2463        frame.set_degradation(DegradationLevel::SimpleBorders);
2464        assert!(frame.should_render_widget(true));
2465        assert!(frame.should_render_widget(false));
2466
2467        frame.set_degradation(DegradationLevel::NoStyling);
2468        assert!(frame.should_render_widget(true));
2469        assert!(frame.should_render_widget(false));
2470
2471        // EssentialOnly: only essential
2472        frame.set_degradation(DegradationLevel::EssentialOnly);
2473        assert!(frame.should_render_widget(true));
2474        assert!(!frame.should_render_widget(false));
2475
2476        // Skeleton: only essential
2477        frame.set_degradation(DegradationLevel::Skeleton);
2478        assert!(frame.should_render_widget(true));
2479        assert!(!frame.should_render_widget(false));
2480
2481        // SkipFrame: none
2482        frame.set_degradation(DegradationLevel::SkipFrame);
2483        assert!(!frame.should_render_widget(true));
2484        assert!(!frame.should_render_widget(false));
2485    }
2486
2487    // --- Frame hit grid with zero-size screen ---
2488
2489    #[test]
2490    fn frame_with_hit_grid_zero_size_clamped_to_one() {
2491        let mut pool = GraphemePool::new();
2492        let frame = Frame::with_hit_grid(0, 0, &mut pool);
2493        assert_eq!(frame.buffer.width(), 1);
2494        assert_eq!(frame.buffer.height(), 1);
2495    }
2496
2497    // --- Frame register_hit returns true/false correctly ---
2498
2499    #[test]
2500    fn frame_register_hit_with_all_regions() {
2501        let mut pool = GraphemePool::new();
2502        let mut frame = Frame::with_hit_grid(20, 20, &mut pool);
2503        let regions = [
2504            HitRegion::Content,
2505            HitRegion::Border,
2506            HitRegion::Scrollbar,
2507            HitRegion::Handle,
2508            HitRegion::Button,
2509            HitRegion::Link,
2510            HitRegion::Custom(0),
2511            HitRegion::Custom(255),
2512        ];
2513        for (i, &region) in regions.iter().enumerate() {
2514            let y = i as u16;
2515            frame.register_hit(Rect::new(0, y, 1, 1), HitId::new(i as u32), region, 0);
2516        }
2517        for (i, &region) in regions.iter().enumerate() {
2518            let y = i as u16;
2519            assert_eq!(
2520                frame.hit_test(0, y),
2521                Some((HitId::new(i as u32), region, 0))
2522            );
2523        }
2524    }
2525
2526    // --- Frame Draw trait ---
2527
2528    #[test]
2529    fn frame_draw_horizontal_line() {
2530        let mut pool = GraphemePool::new();
2531        let mut frame = Frame::new(10, 5, &mut pool);
2532        let cell = Cell::from_char('-');
2533        frame.draw_horizontal_line(2, 1, 5, cell);
2534        for x in 2..7 {
2535            assert_eq!(frame.buffer.get(x, 1).unwrap().content.as_char(), Some('-'));
2536        }
2537        // Neighbors untouched
2538        assert!(frame.buffer.get(1, 1).unwrap().is_empty());
2539        assert!(frame.buffer.get(7, 1).unwrap().is_empty());
2540    }
2541
2542    #[test]
2543    fn frame_draw_vertical_line() {
2544        let mut pool = GraphemePool::new();
2545        let mut frame = Frame::new(10, 10, &mut pool);
2546        let cell = Cell::from_char('|');
2547        frame.draw_vertical_line(3, 2, 4, cell);
2548        for y in 2..6 {
2549            assert_eq!(frame.buffer.get(3, y).unwrap().content.as_char(), Some('|'));
2550        }
2551        assert!(frame.buffer.get(3, 1).unwrap().is_empty());
2552        assert!(frame.buffer.get(3, 6).unwrap().is_empty());
2553    }
2554
2555    #[test]
2556    fn frame_draw_rect_filled() {
2557        let mut pool = GraphemePool::new();
2558        let mut frame = Frame::new(10, 10, &mut pool);
2559        let cell = Cell::from_char('#');
2560        frame.draw_rect_filled(Rect::new(1, 1, 3, 3), cell);
2561        for y in 1..4 {
2562            for x in 1..4 {
2563                assert_eq!(frame.buffer.get(x, y).unwrap().content.as_char(), Some('#'));
2564            }
2565        }
2566        // Outside
2567        assert!(frame.buffer.get(0, 0).unwrap().is_empty());
2568        assert!(frame.buffer.get(4, 4).unwrap().is_empty());
2569    }
2570
2571    #[test]
2572    fn frame_paint_area() {
2573        use crate::cell::PackedRgba;
2574        let mut pool = GraphemePool::new();
2575        let mut frame = Frame::new(5, 5, &mut pool);
2576        let red = PackedRgba::rgb(255, 0, 0);
2577        frame.paint_area(Rect::new(0, 0, 2, 2), Some(red), None);
2578        let cell = frame.buffer.get(0, 0).unwrap();
2579        assert_eq!(cell.fg, red);
2580    }
2581
2582    // --- Frame print_text_clipped ---
2583
2584    #[test]
2585    fn frame_print_text_clipped_at_boundary() {
2586        let mut pool = GraphemePool::new();
2587        let mut frame = Frame::new(5, 1, &mut pool);
2588        // "Hello World" should be clipped at width 5
2589        let end = frame.print_text(0, 0, "Hello World", Cell::from_char(' '));
2590        assert_eq!(end, 5);
2591        for x in 0..5 {
2592            assert!(!frame.buffer.get(x, 0).unwrap().is_empty());
2593        }
2594    }
2595
2596    #[test]
2597    fn frame_print_text_empty_string() {
2598        let mut pool = GraphemePool::new();
2599        let mut frame = Frame::new(10, 1, &mut pool);
2600        let end = frame.print_text(0, 0, "", Cell::from_char(' '));
2601        assert_eq!(end, 0);
2602    }
2603
2604    #[test]
2605    fn frame_print_text_at_right_edge() {
2606        let mut pool = GraphemePool::new();
2607        let mut frame = Frame::new(5, 1, &mut pool);
2608        // Start at x=4, only 1 cell fits
2609        let end = frame.print_text(4, 0, "AB", Cell::from_char(' '));
2610        assert_eq!(end, 5);
2611        assert_eq!(frame.buffer.get(4, 0).unwrap().content.as_char(), Some('A'));
2612    }
2613
2614    // --- Frame Debug ---
2615
2616    #[test]
2617    fn frame_debug() {
2618        let mut pool = GraphemePool::new();
2619        let frame = Frame::new(5, 3, &mut pool);
2620        let dbg = format!("{:?}", frame);
2621        assert!(dbg.contains("Frame"), "Debug: {dbg}");
2622    }
2623
2624    // --- HitGrid Debug ---
2625
2626    #[test]
2627    fn hit_grid_debug() {
2628        let grid = HitGrid::new(3, 3);
2629        let dbg = format!("{:?}", grid);
2630        assert!(dbg.contains("HitGrid"), "Debug: {dbg}");
2631    }
2632
2633    // --- Frame cursor beyond bounds ---
2634
2635    #[test]
2636    fn frame_cursor_beyond_bounds() {
2637        let mut pool = GraphemePool::new();
2638        let mut frame = Frame::new(10, 10, &mut pool);
2639        // Setting cursor beyond frame is allowed (no clipping)
2640        frame.set_cursor(Some((100, 200)));
2641        assert_eq!(frame.cursor_position, Some((100, 200)));
2642    }
2643
2644    // --- HitGrid large data values ---
2645
2646    #[test]
2647    fn hit_grid_register_overwrite() {
2648        let mut grid = HitGrid::new(5, 5);
2649        grid.register(Rect::new(0, 0, 3, 3), HitId::new(1), HitRegion::Content, 10);
2650        grid.register(Rect::new(0, 0, 3, 3), HitId::new(2), HitRegion::Button, 20);
2651        // Second registration overwrites first
2652        assert_eq!(
2653            grid.hit_test(1, 1),
2654            Some((HitId::new(2), HitRegion::Button, 20))
2655        );
2656    }
2657
2658    #[test]
2659    fn frame_hit_test_detailed_preserves_owner() {
2660        let mut pool = GraphemePool::new();
2661        let mut frame = Frame::with_hit_grid(4, 4, &mut pool);
2662
2663        frame.with_hit_owner(77, |frame| {
2664            frame.register_hit(Rect::new(1, 1, 2, 2), HitId::new(5), HitRegion::Button, 9);
2665        });
2666
2667        assert_eq!(
2668            frame.hit_test_detailed(1, 1),
2669            Some(HitTestResult::new(
2670                HitId::new(5),
2671                HitRegion::Button,
2672                9,
2673                Some(77),
2674            ))
2675        );
2676        assert_eq!(
2677            frame.hit_test(1, 1),
2678            Some((HitId::new(5), HitRegion::Button, 9))
2679        );
2680    }
2681
2682    #[test]
2683    fn frame_hit_owner_scope_restores_previous_owner() {
2684        let mut pool = GraphemePool::new();
2685        let mut frame = Frame::with_hit_grid(4, 4, &mut pool);
2686
2687        frame.with_hit_owner(10, |frame| {
2688            frame.register_hit(Rect::new(0, 0, 1, 1), HitId::new(1), HitRegion::Content, 1);
2689            frame.with_hit_owner(20, |frame| {
2690                frame.register_hit(Rect::new(1, 0, 1, 1), HitId::new(2), HitRegion::Content, 2);
2691            });
2692            frame.register_hit(Rect::new(2, 0, 1, 1), HitId::new(3), HitRegion::Content, 3);
2693        });
2694
2695        assert_eq!(frame.hit_test_detailed(0, 0).unwrap().owner, Some(10));
2696        assert_eq!(frame.hit_test_detailed(1, 0).unwrap().owner, Some(20));
2697        assert_eq!(frame.hit_test_detailed(2, 0).unwrap().owner, Some(10));
2698    }
2699
2700    #[test]
2701    fn frame_hit_owner_scope_restores_after_panic() {
2702        let mut pool = GraphemePool::new();
2703        let mut frame = Frame::with_hit_grid(4, 4, &mut pool);
2704
2705        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2706            frame.with_hit_owner(55, |_frame| panic!("boom"));
2707        }));
2708        assert!(result.is_err());
2709
2710        frame.register_hit(Rect::new(0, 0, 1, 1), HitId::new(9), HitRegion::Content, 0);
2711        assert_eq!(frame.hit_test_detailed(0, 0).unwrap().owner, None);
2712    }
2713}