Skip to main content

repose_core/
runtime.rs

1use std::any::Any;
2use std::cell::{Cell, RefCell};
3use std::collections::HashMap;
4use std::rc::Rc;
5
6use crate::scope::Scope;
7use crate::{Rect, Scene, View, semantics::Role};
8
9thread_local! {
10    pub static COMPOSER: RefCell<Composer> = RefCell::new(Composer::default());
11    static ROOT_SCOPE: RefCell<Option<Scope>> = const { RefCell::new(None) };
12
13    /// A programmatic focus request, set by `FocusRequester::request_focus()`.
14    /// Stores the view ID that should receive focus on the next frame.
15    static FOCUS_REQUEST: Cell<Option<u64>> = const { Cell::new(None) };
16}
17
18pub fn take_focus_request() -> Option<u64> {
19    FOCUS_REQUEST.with(|r| r.replace(None))
20}
21
22/// A handle that can programmatically request focus for a widget.
23///
24/// Similar to Compose's `FocusRequester`. Create one via `remember(FocusRequester::new)`,
25/// attach it via `.focus_requester(...)` on a modifier, and call `request_focus()` to
26/// move keyboard focus to the associated widget on the next frame.
27#[derive(Clone)]
28pub struct FocusRequester {
29    /// Target view ID, set during layout/paint by the modifier system.
30    pub target: Rc<RefCell<Option<u64>>>,
31}
32
33impl FocusRequester {
34    pub fn new() -> Self {
35        Self {
36            target: Rc::new(RefCell::new(None)),
37        }
38    }
39
40    /// Request focus for the associated widget on the next frame.
41    pub fn request_focus(&self) {
42        if let Some(id) = *self.target.borrow() {
43            FOCUS_REQUEST.with(|r| r.set(Some(id)));
44        }
45    }
46}
47
48impl Default for FocusRequester {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54/// Direction for focus movement.
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum FocusDirection {
57    Next,
58    Previous,
59    Left,
60    Right,
61    Up,
62    Down,
63}
64
65/// A manager for programmatic focus navigation.
66///
67/// Wraps a `&Scheduler` and provides methods to move focus.
68/// Can also be used standalone with a focus chain and focused element.
69#[derive(Clone)]
70pub struct FocusManager {
71    /// The ordered list of focusable element IDs.
72    pub chain: Vec<u64>,
73    /// The currently focused element (if any).
74    pub focused: Option<u64>,
75}
76
77impl FocusManager {
78    pub fn new(chain: Vec<u64>, focused: Option<u64>) -> Self {
79        Self { chain, focused }
80    }
81
82    /// Move focus in the given direction.
83    /// Returns the new focused element ID, or `None` if no movement is possible.
84    pub fn move_focus(&mut self, dir: FocusDirection) -> Option<u64> {
85        match dir {
86            FocusDirection::Next | FocusDirection::Previous => {
87                self.move_tab(dir == FocusDirection::Previous)
88            }
89            _ => None, // use move_focus_spatial when hit regions are available
90        }
91    }
92
93    /// Spatial focus navigation: find the closest focusable element in a given
94    /// direction using bounding rect geometry.
95    pub fn move_focus_spatial(
96        &mut self,
97        dir: FocusDirection,
98        hit_regions: &[HitRegion],
99    ) -> Option<u64> {
100        let next = spatial_focus_next(&self.chain, hit_regions, self.focused, dir)?;
101        self.focused = Some(next);
102        Some(next)
103    }
104
105    /// Tab forward or backward in the focus chain.
106    pub fn move_tab(&mut self, reverse: bool) -> Option<u64> {
107        if self.chain.is_empty() {
108            return None;
109        }
110        let next = if let Some(cur) = self.focused {
111            if let Some(idx) = self.chain.iter().position(|&id| id == cur) {
112                if reverse {
113                    if idx == 0 {
114                        self.chain[self.chain.len() - 1]
115                    } else {
116                        self.chain[idx - 1]
117                    }
118                } else {
119                    self.chain[(idx + 1) % self.chain.len()]
120                }
121            } else {
122                self.chain[0]
123            }
124        } else {
125            self.chain[0]
126        };
127        self.focused = Some(next);
128        Some(next)
129    }
130
131    /// Set target ID on a FocusRequester (called during layout).
132    pub fn set_requester_target(requester: &FocusRequester, id: u64) {
133        *requester.target.borrow_mut() = Some(id);
134    }
135}
136
137/// Find the next focusable element in a given spatial direction.
138///
139/// Uses the bounding rects from `hit_regions` to determine which element is
140/// "next" in the given direction from the currently focused element.
141pub fn spatial_focus_next(
142    chain: &[u64],
143    hit_regions: &[HitRegion],
144    current: Option<u64>,
145    dir: FocusDirection,
146) -> Option<u64> {
147    if chain.is_empty() {
148        return None;
149    }
150
151    let current_rect = current.and_then(|id| hit_regions.iter().find(|h| h.id == id).map(|h| h.rect));
152
153    // For Next/Previous, use tab-order navigation
154    match dir {
155        FocusDirection::Next | FocusDirection::Previous => {
156            let mut fm = FocusManager {
157                chain: chain.to_vec(),
158                focused: current,
159            };
160            return fm.move_tab(dir == FocusDirection::Previous);
161        }
162        _ => {}
163    }
164
165    let (cx, cy) = match current_rect {
166        Some(r) => (r.x + r.w / 2.0, r.y + r.h / 2.0),
167        None => return chain.first().copied(),
168    };
169
170    let mut best: Option<(u64, f32)> = None;
171
172    for &id in chain {
173        if Some(id) == current {
174            continue;
175        }
176        let Some(hr) = hit_regions.iter().find(|h| h.id == id) else {
177            continue;
178        };
179        let r = hr.rect;
180        let other_cx = r.x + r.w / 2.0;
181        let other_cy = r.y + r.h / 2.0;
182        let dx = other_cx - cx;
183        let dy = other_cy - cy;
184
185        let in_direction = match dir {
186            FocusDirection::Left => dx < 0.0 && dy.abs() <= r.h.max(1.0),
187            FocusDirection::Right => dx > 0.0 && dy.abs() <= r.h.max(1.0),
188            FocusDirection::Up => dy < 0.0 && dx.abs() <= r.w.max(1.0),
189            FocusDirection::Down => dy > 0.0 && dx.abs() <= r.w.max(1.0),
190            _ => false,
191        };
192
193        if !in_direction {
194            continue;
195        }
196
197        let dist = dx * dx + dy * dy;
198        let weight = dist / (r.w * r.h + 1.0).max(1.0);
199
200        match best {
201            Some((_, best_weight)) if weight >= best_weight => {}
202            _ => best = Some((id, weight)),
203        }
204    }
205
206    best.map(|(id, _)| id)
207}
208
209#[derive(Default)]
210pub struct Composer {
211    pub slots: Vec<Box<dyn Any>>,
212    pub cursor: usize,
213    pub keyed_slots: HashMap<String, Box<dyn Any>>,
214}
215
216pub struct ComposeGuard {
217    scope: Scope,
218}
219
220impl ComposeGuard {
221    pub fn begin() -> Self {
222        COMPOSER.with(|c| c.borrow_mut().cursor = 0);
223
224        let scope = ROOT_SCOPE.with(|rs| {
225            if let Some(existing) = rs.borrow().clone() {
226                existing
227            } else {
228                let s = Scope::new();
229                *rs.borrow_mut() = Some(s.clone());
230                s
231            }
232        });
233
234        ComposeGuard { scope }
235    }
236
237    pub fn scope(&self) -> &Scope {
238        &self.scope
239    }
240}
241
242impl Drop for ComposeGuard {
243    fn drop(&mut self) {
244        // ROOT_SCOPE.with(|rs| { Do not clear every frame
245        //     *rs.borrow_mut() = None;
246        // });
247    }
248}
249
250/// Slot-based remember (sequential composition only)
251pub fn remember<T: 'static>(init: impl FnOnce() -> T) -> Rc<T> {
252    COMPOSER.with(|c| {
253        let mut c = c.borrow_mut();
254        let cursor = c.cursor;
255        c.cursor += 1;
256
257        if cursor >= c.slots.len() {
258            let rc: Rc<T> = Rc::new(init());
259            c.slots.push(Box::new(rc.clone()));
260            return rc;
261        }
262
263        if let Some(rc) = c.slots[cursor].downcast_ref::<Rc<T>>() {
264            rc.clone()
265        } else {
266            // replace (else panics)
267            log::warn!(
268                "remember: slot {} type changed; replacing. \
269                 If this is due to conditional composition, prefer remember_with_key.",
270                cursor
271            );
272            let rc: Rc<T> = Rc::new(init());
273            c.slots[cursor] = Box::new(rc.clone());
274            rc
275        }
276    })
277}
278
279/// Key-based remember
280pub fn remember_with_key<T: 'static>(key: impl Into<String>, init: impl FnOnce() -> T) -> Rc<T> {
281    COMPOSER.with(|c| {
282        let mut c = c.borrow_mut();
283        let key = key.into();
284
285        if let Some(existing) = c.keyed_slots.get(&key) {
286            if let Some(rc) = existing.downcast_ref::<Rc<T>>() {
287                return rc.clone();
288            } else {
289                log::warn!(
290                    "remember_with_key: key '{}' reused with a different type; replacing.",
291                    key
292                );
293            }
294        }
295
296        if cfg!(debug_assertions) && c.keyed_slots.len() > 10_000 {
297            log::warn!(
298                "remember_with_key: more than 10k keys stored; \
299                are you generating unbounded dynamic keys (e.g., using timestamps)?"
300            );
301        }
302
303        let rc: Rc<T> = Rc::new(init());
304        c.keyed_slots.insert(key, Box::new(rc.clone()));
305        rc
306    })
307}
308
309pub fn remember_state<T: 'static>(init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
310    remember(|| RefCell::new(init()))
311}
312
313pub fn remember_state_with_key<T: 'static>(
314    key: impl Into<String>,
315    init: impl FnOnce() -> T,
316) -> Rc<RefCell<T>> {
317    remember_with_key(key, || RefCell::new(init()))
318}
319
320/// Frame - output of composition for a tick: scene + input/semantics.
321pub struct Frame {
322    pub scene: Scene,
323    pub hit_regions: Vec<HitRegion>,
324    pub semantics_nodes: Vec<SemNode>,
325    pub focus_chain: Vec<u64>,
326}
327
328#[derive(Clone, Default)]
329pub struct HitRegion {
330    pub id: u64,
331    pub rect: Rect,
332    pub on_click: Option<Rc<dyn Fn()>>,
333    pub on_scroll: Option<Rc<dyn Fn(crate::Vec2) -> crate::Vec2>>,
334    pub focusable: bool,
335    pub on_pointer_down: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
336    pub on_pointer_move: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
337    pub on_pointer_up: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
338    pub on_pointer_enter: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
339    pub on_pointer_leave: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
340    pub z_index: f32,
341    pub on_text_change: Option<Rc<dyn Fn(String)>>,
342    pub on_text_submit: Option<Rc<dyn Fn(String)>>,
343    /// If this hit region belongs to a TextField, this persistent key is used
344    /// for looking up platform-managed TextFieldState. Falls back to `id` if None.
345    pub tf_state_key: Option<u64>,
346
347    /// True if this hit region corresponds to a multiline text input (TextArea).
348    pub tf_multiline: bool,
349
350    // internal
351    pub on_drag_start: Option<Rc<dyn Fn(crate::dnd::DragStart) -> Option<crate::dnd::DragPayload>>>,
352    pub on_drag_end: Option<Rc<dyn Fn(crate::dnd::DragEnd)>>,
353    pub on_drag_enter: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
354    pub on_drag_over: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
355    pub on_drag_leave: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
356    pub on_drop: Option<Rc<dyn Fn(crate::dnd::DropEvent) -> bool>>,
357
358    pub on_action: Option<Rc<dyn Fn(crate::shortcuts::Action) -> bool>>,
359
360    /// Cursor hint for desktop/web.
361    pub cursor: Option<crate::CursorIcon>,
362}
363
364impl HitRegion {
365    /// Seed a HitRegion with all the modifier's event handlers + dnd + cursor.
366    /// Call‑sites should only override the fields that differ (on_click, focusable, etc.)
367    /// via struct‑update syntax: `HitRegion { focusable: true, ..from_modifier(..) }`.
368    pub fn from_modifier(id: u64, rect: Rect, m: &crate::modifier::Modifier) -> Self {
369        Self {
370            id,
371            rect,
372            z_index: m.z_index,
373            on_pointer_down: m.on_pointer_down.clone(),
374            on_pointer_move: m.on_pointer_move.clone(),
375            on_pointer_up: m.on_pointer_up.clone(),
376            on_pointer_enter: m.on_pointer_enter.clone(),
377            on_pointer_leave: m.on_pointer_leave.clone(),
378            on_action: m.on_action.clone(),
379            cursor: m.cursor,
380            on_drag_start: m.on_drag_start.clone(),
381            on_drag_end: m.on_drag_end.clone(),
382            on_drag_enter: m.on_drag_enter.clone(),
383            on_drag_over: m.on_drag_over.clone(),
384            on_drag_leave: m.on_drag_leave.clone(),
385            on_drop: m.on_drop.clone(),
386            ..Default::default()
387        }
388    }
389}
390
391/// Flattened semantics node produced by `layout_and_paint`.
392///
393/// This is the source of truth for accessibility backends: it contains the
394/// resolved screen rect, role, label, and focus/enabled state.
395///
396/// The platform runner should convert this into OS‑specific accessibility trees (when implemented)
397/// (AT‑SPI on Linux, TalkBack on Android, etc.).
398#[derive(Clone)]
399pub struct SemNode {
400    /// Stable id, shared with the associated `HitRegion` / `ViewId`.
401    pub id: u64,
402
403    /// `None` means direct child of the window root.
404    pub parent: Option<u64>,
405
406    pub role: Role,
407    pub label: Option<String>,
408    pub rect: Rect,
409    pub focused: bool,
410    pub enabled: bool,
411}
412
413pub struct Scheduler {
414    next_id: u64,
415    pub focused: Option<u64>,
416    pub size: (u32, u32),
417}
418
419impl Default for Scheduler {
420    fn default() -> Self {
421        Self::new()
422    }
423}
424
425impl Scheduler {
426    pub fn new() -> Self {
427        Self {
428            next_id: 1,
429            focused: None,
430            size: (1280, 800),
431        }
432    }
433
434    pub fn id(&mut self) -> u64 {
435        let id = self.next_id;
436        self.next_id += 1;
437        id
438    }
439
440    pub fn id_count(&self) -> u64 {
441        self.next_id - 1
442    }
443
444    pub fn repose<F>(
445        &mut self,
446        mut build_root: F,
447        layout_paint: impl Fn(&View, (u32, u32)) -> (Scene, Vec<HitRegion>, Vec<SemNode>),
448    ) -> Frame
449    where
450        F: FnMut(&mut Scheduler) -> View,
451    {
452        let guard = ComposeGuard::begin();
453        let root = guard.scope.run(|| build_root(self));
454        let (scene, hits, sem) = layout_paint(&root, self.size);
455
456        let focus_chain: Vec<u64> = hits.iter().filter(|h| h.focusable).map(|h| h.id).collect();
457
458        Frame {
459            scene,
460            hit_regions: hits,
461            semantics_nodes: sem,
462            focus_chain,
463        }
464    }
465}
466
467/// Avoids cross-test pollution
468#[cfg(test)]
469pub fn clear_composer() {
470    COMPOSER.with(|c| {
471        let mut c = c.borrow_mut();
472        c.slots.clear();
473        c.keyed_slots.clear();
474        c.cursor = 0;
475    });
476    ROOT_SCOPE.with(|rs| {
477        *rs.borrow_mut() = None;
478    });
479}