repose_core/
runtime.rs

1use std::any::Any;
2use std::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>> = RefCell::new(None);
12}
13
14#[derive(Default)]
15pub struct Composer {
16    pub slots: Vec<Box<dyn Any>>,
17    pub cursor: usize,
18    pub keyed_slots: HashMap<String, Box<dyn Any>>,
19}
20
21pub struct ComposeGuard {
22    scope: Scope,
23}
24
25impl ComposeGuard {
26    pub fn begin() -> Self {
27        let scope = Scope::new();
28
29        COMPOSER.with(|c| {
30            let mut c = c.borrow_mut();
31            c.cursor = 0;
32        });
33
34        ROOT_SCOPE.with(|rs| {
35            *rs.borrow_mut() = Some(scope.clone());
36        });
37
38        ComposeGuard { scope }
39    }
40
41    pub fn scope(&self) -> &Scope {
42        &self.scope
43    }
44}
45
46impl Drop for ComposeGuard {
47    fn drop(&mut self) {
48        ROOT_SCOPE.with(|rs| {
49            *rs.borrow_mut() = None;
50        });
51    }
52}
53
54/// Slot-based remember (sequential composition only)
55pub fn remember<T: 'static>(init: impl FnOnce() -> T) -> Rc<T> {
56    COMPOSER.with(|c| {
57        let mut c = c.borrow_mut();
58        let cursor = c.cursor;
59        c.cursor += 1;
60
61        if cursor >= c.slots.len() {
62            let rc: Rc<T> = Rc::new(init());
63            c.slots.push(Box::new(rc.clone()));
64            return rc;
65        }
66
67        if let Some(rc) = c.slots[cursor].downcast_ref::<Rc<T>>() {
68            rc.clone()
69        } else {
70            // replace (else panics)
71            log::warn!(
72                "remember: slot {} type changed; replacing. \
73                 If this is due to conditional composition, prefer remember_with_key.",
74                cursor
75            );
76            let rc: Rc<T> = Rc::new(init());
77            c.slots[cursor] = Box::new(rc.clone());
78            rc
79        }
80    })
81}
82
83/// Key-based remember
84pub fn remember_with_key<T: 'static>(key: impl Into<String>, init: impl FnOnce() -> T) -> Rc<T> {
85    COMPOSER.with(|c| {
86        let mut c = c.borrow_mut();
87        let key = key.into();
88
89        if let Some(existing) = c.keyed_slots.get(&key) {
90            if let Some(rc) = existing.downcast_ref::<Rc<T>>() {
91                return rc.clone();
92            } else {
93                log::warn!(
94                    "remember_with_key: key '{}' reused with a different type; replacing.",
95                    key
96                );
97            }
98        }
99
100        let rc: Rc<T> = Rc::new(init());
101        c.keyed_slots.insert(key, Box::new(rc.clone()));
102        rc
103    })
104}
105
106pub fn remember_state<T: 'static>(init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
107    remember(|| RefCell::new(init()))
108}
109
110pub fn remember_state_with_key<T: 'static>(
111    key: impl Into<String>,
112    init: impl FnOnce() -> T,
113) -> Rc<RefCell<T>> {
114    remember_with_key(key, || RefCell::new(init()))
115}
116
117/// Frame — output of composition for a tick: scene + input/semantics.
118pub struct Frame {
119    pub scene: Scene,
120    pub hit_regions: Vec<HitRegion>,
121    pub semantics_nodes: Vec<SemNode>,
122    pub focus_chain: Vec<u64>,
123}
124
125#[derive(Clone)]
126pub struct HitRegion {
127    pub id: u64,
128    pub rect: Rect,
129    pub on_click: Option<Rc<dyn Fn()>>,
130    pub on_scroll: Option<Rc<dyn Fn(crate::Vec2) -> crate::Vec2>>,
131    pub focusable: bool,
132    pub on_pointer_down: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
133    pub on_pointer_move: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
134    pub on_pointer_up: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
135    pub on_pointer_enter: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
136    pub on_pointer_leave: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
137    pub z_index: f32,
138    pub on_text_change: Option<Rc<dyn Fn(String)>>,
139    pub on_text_submit: Option<Rc<dyn Fn(String)>>,
140    /// If this hit region belongs to a TextField, this persistent key is used
141    /// for looking up platform-managed TextFieldState. Falls back to `id` if None.
142    pub tf_state_key: Option<u64>,
143}
144
145#[derive(Clone)]
146pub struct SemNode {
147    pub id: u64,
148    pub role: Role,
149    pub label: Option<String>,
150    pub rect: Rect,
151    pub focused: bool,
152    pub enabled: bool,
153}
154
155pub struct Scheduler {
156    next_id: u64,
157    pub focused: Option<u64>,
158    pub size: (u32, u32),
159}
160
161impl Scheduler {
162    pub fn new() -> Self {
163        Self {
164            next_id: 1,
165            focused: None,
166            size: (1280, 800),
167        }
168    }
169
170    pub fn id(&mut self) -> u64 {
171        let id = self.next_id;
172        self.next_id += 1;
173        id
174    }
175
176    pub fn repose<F>(
177        &mut self,
178        mut build_root: F,
179        layout_paint: impl Fn(&View, (u32, u32)) -> (Scene, Vec<HitRegion>, Vec<SemNode>),
180    ) -> Frame
181    where
182        F: FnMut(&mut Scheduler) -> View,
183    {
184        let guard = ComposeGuard::begin();
185        let root = guard.scope.run(|| build_root(self));
186        let (scene, hits, sem) = layout_paint(&root, self.size);
187
188        let focus_chain: Vec<u64> = hits.iter().filter(|h| h.focusable).map(|h| h.id).collect();
189
190        Frame {
191            scene,
192            hit_regions: hits,
193            semantics_nodes: sem,
194            focus_chain,
195        }
196    }
197}