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 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#[derive(Clone)]
28pub struct FocusRequester {
29 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 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
56pub enum FocusDirection {
57 Next,
58 Previous,
59 Left,
60 Right,
61 Up,
62 Down,
63}
64
65#[derive(Clone)]
70pub struct FocusManager {
71 pub chain: Vec<u64>,
73 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 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, }
91 }
92
93 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 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 pub fn set_requester_target(requester: &FocusRequester, id: u64) {
133 *requester.target.borrow_mut() = Some(id);
134 }
135}
136
137pub 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 =
152 current.and_then(|id| hit_regions.iter().find(|h| h.id == id).map(|h| h.rect));
153
154 match dir {
156 FocusDirection::Next | FocusDirection::Previous => {
157 let mut fm = FocusManager {
158 chain: chain.to_vec(),
159 focused: current,
160 };
161 return fm.move_tab(dir == FocusDirection::Previous);
162 }
163 _ => {}
164 }
165
166 let (cx, cy) = match current_rect {
167 Some(r) => (r.x + r.w / 2.0, r.y + r.h / 2.0),
168 None => return chain.first().copied(),
169 };
170
171 let mut best: Option<(u64, f32)> = None;
172
173 for &id in chain {
174 if Some(id) == current {
175 continue;
176 }
177 let Some(hr) = hit_regions.iter().find(|h| h.id == id) else {
178 continue;
179 };
180 let r = hr.rect;
181 let other_cx = r.x + r.w / 2.0;
182 let other_cy = r.y + r.h / 2.0;
183 let dx = other_cx - cx;
184 let dy = other_cy - cy;
185
186 let in_direction = match dir {
187 FocusDirection::Left => dx < 0.0 && dy.abs() <= r.h.max(1.0),
188 FocusDirection::Right => dx > 0.0 && dy.abs() <= r.h.max(1.0),
189 FocusDirection::Up => dy < 0.0 && dx.abs() <= r.w.max(1.0),
190 FocusDirection::Down => dy > 0.0 && dx.abs() <= r.w.max(1.0),
191 _ => false,
192 };
193
194 if !in_direction {
195 continue;
196 }
197
198 let dist = dx * dx + dy * dy;
199 let weight = dist / (r.w * r.h + 1.0).max(1.0);
200
201 match best {
202 Some((_, best_weight)) if weight >= best_weight => {}
203 _ => best = Some((id, weight)),
204 }
205 }
206
207 best.map(|(id, _)| id)
208}
209
210#[derive(Default)]
211pub struct Composer {
212 pub slots: Vec<Box<dyn Any>>,
213 pub cursor: usize,
214 pub keyed_slots: HashMap<String, Box<dyn Any>>,
215}
216
217pub struct ComposeGuard {
218 scope: Scope,
219}
220
221impl ComposeGuard {
222 pub fn begin() -> Self {
223 COMPOSER.with(|c| c.borrow_mut().cursor = 0);
224
225 let scope = ROOT_SCOPE.with(|rs| {
226 if let Some(existing) = rs.borrow().clone() {
227 existing
228 } else {
229 let s = Scope::new();
230 *rs.borrow_mut() = Some(s.clone());
231 s
232 }
233 });
234
235 ComposeGuard { scope }
236 }
237
238 pub fn scope(&self) -> &Scope {
239 &self.scope
240 }
241}
242
243impl Drop for ComposeGuard {
244 fn drop(&mut self) {
245 }
249}
250
251pub fn remember<T: 'static>(init: impl FnOnce() -> T) -> Rc<T> {
253 COMPOSER.with(|c| {
254 let mut c = c.borrow_mut();
255 let cursor = c.cursor;
256 c.cursor += 1;
257
258 if cursor >= c.slots.len() {
259 let rc: Rc<T> = Rc::new(init());
260 c.slots.push(Box::new(rc.clone()));
261 return rc;
262 }
263
264 if let Some(rc) = c.slots[cursor].downcast_ref::<Rc<T>>() {
265 rc.clone()
266 } else {
267 log::warn!(
269 "remember: slot {} type changed; replacing. \
270 If this is due to conditional composition, prefer remember_with_key.",
271 cursor
272 );
273 let rc: Rc<T> = Rc::new(init());
274 c.slots[cursor] = Box::new(rc.clone());
275 rc
276 }
277 })
278}
279
280pub fn remember_with_key<T: 'static>(key: impl Into<String>, init: impl FnOnce() -> T) -> Rc<T> {
282 COMPOSER.with(|c| {
283 let mut c = c.borrow_mut();
284 let key = key.into();
285
286 if let Some(existing) = c.keyed_slots.get(&key) {
287 if let Some(rc) = existing.downcast_ref::<Rc<T>>() {
288 return rc.clone();
289 } else {
290 log::warn!(
291 "remember_with_key: key '{}' reused with a different type; replacing.",
292 key
293 );
294 }
295 }
296
297 if cfg!(debug_assertions) && c.keyed_slots.len() > 10_000 {
298 log::warn!(
299 "remember_with_key: more than 10k keys stored; \
300 are you generating unbounded dynamic keys (e.g., using timestamps)?"
301 );
302 }
303
304 let rc: Rc<T> = Rc::new(init());
305 c.keyed_slots.insert(key, Box::new(rc.clone()));
306 rc
307 })
308}
309
310pub fn remember_state<T: 'static>(init: impl FnOnce() -> T) -> Rc<RefCell<T>> {
311 remember(|| RefCell::new(init()))
312}
313
314pub fn remember_state_with_key<T: 'static>(
315 key: impl Into<String>,
316 init: impl FnOnce() -> T,
317) -> Rc<RefCell<T>> {
318 remember_with_key(key, || RefCell::new(init()))
319}
320
321pub struct Frame {
323 pub scene: Scene,
324 pub hit_regions: Vec<HitRegion>,
325 pub semantics_nodes: Vec<SemNode>,
326 pub focus_chain: Vec<u64>,
327}
328
329#[derive(Clone, Default)]
330pub struct HitRegion {
331 pub id: u64,
332 pub rect: Rect,
333 pub on_click: Option<Rc<dyn Fn()>>,
334 pub on_scroll: Option<Rc<dyn Fn(crate::Vec2) -> crate::Vec2>>,
335 pub focusable: bool,
336 pub on_pointer_down: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
337 pub on_pointer_move: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
338 pub on_pointer_up: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
339 pub on_pointer_enter: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
340 pub on_pointer_leave: Option<Rc<dyn Fn(crate::input::PointerEvent)>>,
341 pub z_index: f32,
342 pub on_text_change: Option<Rc<dyn Fn(String)>>,
343 pub on_text_submit: Option<Rc<dyn Fn(String)>>,
344 pub tf_state_key: Option<u64>,
347
348 pub tf_multiline: bool,
350
351 pub on_drag_start: Option<Rc<dyn Fn(crate::dnd::DragStart) -> Option<crate::dnd::DragPayload>>>,
353 pub on_drag_end: Option<Rc<dyn Fn(crate::dnd::DragEnd)>>,
354 pub on_drag_enter: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
355 pub on_drag_over: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
356 pub on_drag_leave: Option<Rc<dyn Fn(crate::dnd::DragOver)>>,
357 pub on_drop: Option<Rc<dyn Fn(crate::dnd::DropEvent) -> bool>>,
358
359 pub on_action: Option<Rc<dyn Fn(crate::shortcuts::Action) -> bool>>,
360
361 pub cursor: Option<crate::CursorIcon>,
363}
364
365impl HitRegion {
366 pub fn from_modifier(id: u64, rect: Rect, m: &crate::modifier::Modifier) -> Self {
370 Self {
371 id,
372 rect,
373 z_index: m.z_index,
374 on_pointer_down: m.on_pointer_down.clone(),
375 on_pointer_move: m.on_pointer_move.clone(),
376 on_pointer_up: m.on_pointer_up.clone(),
377 on_pointer_enter: m.on_pointer_enter.clone(),
378 on_pointer_leave: m.on_pointer_leave.clone(),
379 on_action: m.on_action.clone(),
380 cursor: m.cursor,
381 on_drag_start: m.on_drag_start.clone(),
382 on_drag_end: m.on_drag_end.clone(),
383 on_drag_enter: m.on_drag_enter.clone(),
384 on_drag_over: m.on_drag_over.clone(),
385 on_drag_leave: m.on_drag_leave.clone(),
386 on_drop: m.on_drop.clone(),
387 ..Default::default()
388 }
389 }
390}
391
392#[derive(Clone)]
400pub struct SemNode {
401 pub id: u64,
403
404 pub parent: Option<u64>,
406
407 pub role: Role,
408 pub label: Option<String>,
409 pub rect: Rect,
410 pub focused: bool,
411 pub enabled: bool,
412}
413
414pub struct Scheduler {
415 next_id: u64,
416 pub focused: Option<u64>,
417 pub size: (u32, u32),
418}
419
420impl Default for Scheduler {
421 fn default() -> Self {
422 Self::new()
423 }
424}
425
426impl Scheduler {
427 pub fn new() -> Self {
428 Self {
429 next_id: 1,
430 focused: None,
431 size: (1280, 800),
432 }
433 }
434
435 pub fn id(&mut self) -> u64 {
436 let id = self.next_id;
437 self.next_id += 1;
438 id
439 }
440
441 pub fn id_count(&self) -> u64 {
442 self.next_id - 1
443 }
444
445 pub fn repose<F>(
446 &mut self,
447 mut build_root: F,
448 layout_paint: impl Fn(&View, (u32, u32)) -> (Scene, Vec<HitRegion>, Vec<SemNode>),
449 ) -> Frame
450 where
451 F: FnMut(&mut Scheduler) -> View,
452 {
453 let guard = ComposeGuard::begin();
454 let root = guard.scope.run(|| build_root(self));
455 let (scene, hits, sem) = layout_paint(&root, self.size);
456
457 let focus_chain: Vec<u64> = hits.iter().filter(|h| h.focusable).map(|h| h.id).collect();
458
459 Frame {
460 scene,
461 hit_regions: hits,
462 semantics_nodes: sem,
463 focus_chain,
464 }
465 }
466}
467
468#[cfg(test)]
470pub fn clear_composer() {
471 COMPOSER.with(|c| {
472 let mut c = c.borrow_mut();
473 c.slots.clear();
474 c.keyed_slots.clear();
475 c.cursor = 0;
476 });
477 ROOT_SCOPE.with(|rs| {
478 *rs.borrow_mut() = None;
479 });
480}