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