Skip to main content

tui_world/
pointer.rs

1use crate::WidgetId;
2use crate::World;
3use std::collections::HashMap;
4use std::sync::Arc;
5
6pub use crossterm::event::MouseEventKind;
7
8pub type PointerFn = Arc<dyn Fn(&mut World, Area, u16, u16) + Send + Sync>;
9
10/// A rectangular area defined by position and dimensions.
11///
12/// Used to define clickable regions for widgets in the pointer/mouse handling system.
13/// Coordinates are in terminal cell units.
14#[derive(Debug, Clone, Copy)]
15pub struct Area {
16    /// The x-coordinate (column) of the top-left corner.
17    pub x: u16,
18    /// The y-coordinate (row) of the top-left corner.
19    pub y: u16,
20    /// The width of the area in cells.
21    pub width: u16,
22    /// The height of the area in cells.
23    pub height: u16,
24}
25
26impl Area {
27    #[must_use]
28    pub fn new(x: u16, y: u16, width: u16, height: u16) -> Self {
29        Self {
30            x,
31            y,
32            width,
33            height,
34        }
35    }
36
37    #[must_use]
38    pub fn contains(&self, x: u16, y: u16) -> bool {
39        x >= self.x && x < self.x + self.width && y >= self.y && y < self.y + self.height
40    }
41}
42
43impl From<(u16, u16)> for Area {
44    fn from((x, y): (u16, u16)) -> Self {
45        Self::new(x, y, 1, 1)
46    }
47}
48
49#[cfg(feature = "ratatui")]
50impl From<ratatui::layout::Rect> for Area {
51    fn from(rect: ratatui::layout::Rect) -> Self {
52        Self::new(rect.x, rect.y, rect.width, rect.height)
53    }
54}
55
56#[derive(Default)]
57struct Handlers {
58    down: Option<PointerFn>,
59    drag: Option<PointerFn>,
60    up: Option<PointerFn>,
61}
62
63/// Manages mouse/pointer interactions for widgets.
64///
65/// `Pointer` tracks clickable areas for widgets and dispatches mouse events
66/// (down, drag, up) to the appropriate handlers. It maintains a z-order for
67/// hit testing, where later-registered widgets appear on top.
68///
69/// # Example
70///
71/// ```ignore
72/// let mut pointer = Pointer::new();
73/// pointer.set(WidgetId("button"), Area::new(10, 5, 20, 3));
74/// pointer.on_click(WidgetId("button"), |world, area, x, y| {
75///     // Handle click at (x, y) within the button area
76/// });
77/// ```
78pub struct Pointer {
79    order: Vec<WidgetId>,
80    areas: HashMap<WidgetId, Area>,
81    handlers: HashMap<WidgetId, Handlers>,
82    /// Tracks which widget received the last mouse down event
83    active: Option<WidgetId>,
84}
85
86impl Default for Pointer {
87    fn default() -> Self {
88        Self::new()
89    }
90}
91
92impl Pointer {
93    #[must_use]
94    pub fn new() -> Self {
95        Self {
96            order: Vec::new(),
97            areas: HashMap::new(),
98            handlers: HashMap::new(),
99            active: None,
100        }
101    }
102
103    /// Sets the clickable area for a widget.
104    pub fn set<W: Into<Area>>(&mut self, id: WidgetId, area: W) {
105        if !self.areas.contains_key(&id) {
106            self.order.push(id);
107        }
108        self.areas.insert(id, area.into());
109    }
110
111    /// Returns the area for a widget if it exists.
112    #[must_use]
113    pub fn get(&self, id: WidgetId) -> Option<&Area> {
114        self.areas.get(&id)
115    }
116
117    /// Registers a click (mouse down) handler for a widget.
118    pub fn on_click<F>(&mut self, id: WidgetId, handler: F)
119    where
120        F: Fn(&mut World, Area, u16, u16) + Send + Sync + 'static,
121    {
122        self.handlers.entry(id).or_default().down = Some(Arc::new(handler));
123    }
124
125    /// Registers a mouse down handler for a widget.
126    pub fn on_down<F>(&mut self, id: WidgetId, handler: F)
127    where
128        F: Fn(&mut World, Area, u16, u16) + Send + Sync + 'static,
129    {
130        self.on_click(id, handler);
131    }
132
133    /// Registers a drag handler for a widget.
134    /// This is called when mouse moves while button is held down.
135    pub fn on_drag<F>(&mut self, id: WidgetId, handler: F)
136    where
137        F: Fn(&mut World, Area, u16, u16) + Send + Sync + 'static,
138    {
139        self.handlers.entry(id).or_default().drag = Some(Arc::new(handler));
140    }
141
142    /// Registers a mouse up handler for a widget.
143    pub fn on_up<F>(&mut self, id: WidgetId, handler: F)
144    where
145        F: Fn(&mut World, Area, u16, u16) + Send + Sync + 'static,
146    {
147        self.handlers.entry(id).or_default().up = Some(Arc::new(handler));
148    }
149
150    /// Returns the click/down handler for a widget if it exists.
151    #[must_use]
152    pub fn get_handler(&self, id: WidgetId) -> Option<PointerFn> {
153        self.handlers.get(&id).and_then(|h| h.down.clone())
154    }
155
156    /// Removes a widget's area and all handlers.
157    pub fn remove(&mut self, id: WidgetId) {
158        self.areas.remove(&id);
159        self.handlers.remove(&id);
160        self.order.retain(|&i| i != id);
161        if self.active == Some(id) {
162            self.active = None;
163        }
164    }
165
166    /// Performs a hit test to find which widget is at the given coordinates.
167    /// Returns the topmost widget (last in order) that contains the point.
168    #[must_use]
169    pub fn hit_test(&self, x: u16, y: u16) -> Option<WidgetId> {
170        for &id in self.order.iter().rev() {
171            if let Some(area) = self.areas.get(&id)
172                && area.contains(x, y)
173            {
174                return Some(id);
175            }
176        }
177        None
178    }
179
180    /// Performs a hit test and returns the handler if found.
181    #[must_use]
182    pub fn hit_test_handler(&self, x: u16, y: u16) -> Option<(WidgetId, PointerFn)> {
183        self.hit_test(x, y).and_then(|id| {
184            self.handlers
185                .get(&id)
186                .and_then(|h| h.down.clone())
187                .map(|h| (id, h))
188        })
189    }
190
191    /// Sets the active widget (the one that received mouse down).
192    pub fn set_active(&mut self, id: Option<WidgetId>) {
193        self.active = id;
194    }
195
196    /// Returns the currently active widget.
197    #[must_use]
198    pub fn active(&self) -> Option<WidgetId> {
199        self.active
200    }
201
202    /// Gets the handler for a specific event kind and widget.
203    #[must_use]
204    pub fn get_handler_for(&self, id: WidgetId, kind: MouseEventKind) -> Option<PointerFn> {
205        let handlers = self.handlers.get(&id)?;
206        match kind {
207            MouseEventKind::Down(_) => handlers.down.clone(),
208            MouseEventKind::Drag(_) => handlers.drag.clone(),
209            MouseEventKind::Up(_) => handlers.up.clone(),
210            _ => None,
211        }
212    }
213}