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