1use std::cell::RefCell;
9use std::collections::{BTreeMap, BTreeSet};
10use std::rc::{Rc, Weak};
11
12use taffy::TaffyTree;
13
14use crate::a11y::{A11yAction, A11yNode, A11yProps, ActionError, Role};
15use crate::backend::{AvailableSpace, Backend, EventSink, MeasureRequest, NativeState, PlatformMetrics};
16use crate::command::{Command, EventValue, UiEvent};
17use crate::custom::CustomProps;
18use crate::geometry::{Point, Rect, Size, WindowSize};
19use crate::services::{Alert, MenuBar, OpenFile, SaveFile, ServiceError, Services, reply_future};
20use crate::style::{Align, Display, FlexDirection, Style, TextDirection};
21use crate::task::{Clock, Executor, Sleep, TaskHandle};
22use crate::units::ResolveContext;
23use crate::widget::{NodeId, Prop, WidgetKind};
24
25pub(crate) type Handler = Rc<dyn Fn(&UiEvent)>;
26type Handler0 = Rc<dyn Fn()>;
27
28struct Node {
29 kind: WidgetKind,
30 parent: Option<NodeId>,
31 children: Vec<NodeId>,
32 native_children: Vec<NodeId>,
34 native_parent: Option<NodeId>,
35 props: Vec<Prop>,
36 style: Style,
37 a11y: A11yProps,
38 test_id: Option<String>,
39 tab_index: Option<u32>,
40 handlers: Vec<Handler>,
41 taffy: Option<taffy::NodeId>,
42 frame: Rect,
44 window_size: Size,
46 fit_height: bool,
48 scroll_offset: Point,
50}
51
52impl Node {
53 fn prop(&self, key: &Prop) -> Option<&Prop> {
54 self.props.iter().find(|p| p.key() == key.key())
55 }
56
57 fn custom(&self) -> Option<&CustomProps> {
58 self.props.iter().find_map(|p| match p {
59 Prop::Custom(custom) => Some(custom),
60 _ => None,
61 })
62 }
63
64 fn drawn(&self) -> Option<&CustomProps> {
66 self.custom().filter(|c| c.is_drawn())
67 }
68}
69
70struct Inner {
71 backend: Box<dyn Backend>,
72 events: EventSink,
73 metrics: PlatformMetrics,
74 nodes: BTreeMap<NodeId, Node>,
75 taffy: TaffyTree<NodeId>,
76 next_id: u32,
77 pending: Vec<Command>,
78 pending_focus: Vec<NodeId>,
81 windows: Vec<NodeId>,
82 styles_dirty: bool,
83 resync: BTreeSet<NodeId>,
84 menu_handlers: std::collections::HashMap<u32, Handler0>,
85 menu_queue: std::collections::VecDeque<u32>,
86 focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
88 focused: BTreeMap<NodeId, NodeId>,
90 commit_scheduler: Option<Rc<dyn Fn()>>,
91 commit_scheduled: bool,
92}
93
94#[derive(Clone)]
97pub struct Ui {
98 inner: Rc<RefCell<Inner>>,
99 executor: Rc<Executor>,
101 services: Rc<RefCell<Box<dyn Services>>>,
103}
104
105#[derive(Clone)]
107pub struct WeakUi {
108 inner: Weak<RefCell<Inner>>,
109 executor: Weak<Executor>,
110 services: Weak<RefCell<Box<dyn Services>>>,
111}
112
113impl WeakUi {
114 pub fn upgrade(&self) -> Option<Ui> {
115 Some(Ui {
116 inner: self.inner.upgrade()?,
117 executor: self.executor.upgrade()?,
118 services: self.services.upgrade()?,
119 })
120 }
121}
122
123#[derive(Clone, Debug, PartialEq)]
125pub struct NodeInfo {
126 pub id: NodeId,
127 pub kind: WidgetKind,
128 pub props: Vec<Prop>,
129 pub test_id: Option<String>,
130 pub frame: Rect,
132 pub children: Vec<NodeInfo>,
133}
134
135impl Ui {
136 pub fn new(backend: impl Backend + 'static) -> Ui {
137 let mut backend: Box<dyn Backend> = Box::new(backend);
138 let events = EventSink::default();
139 backend.init(events.clone());
140 let metrics = backend.metrics();
141 let services = Rc::new(RefCell::new(backend.services()));
142 Ui {
143 executor: Rc::default(),
144 services,
145 inner: Rc::new(RefCell::new(Inner {
146 backend,
147 events,
148 metrics,
149 nodes: BTreeMap::new(),
150 taffy: TaffyTree::new(),
151 next_id: 1,
152 pending: Vec::new(),
153 pending_focus: Vec::new(),
154 windows: Vec::new(),
155 styles_dirty: true,
156 resync: BTreeSet::new(),
157 focus_orders: BTreeMap::new(),
158 focused: BTreeMap::new(),
159 menu_handlers: Default::default(),
160 menu_queue: Default::default(),
161 commit_scheduler: None,
162 commit_scheduled: false,
163 })),
164 }
165 }
166
167 pub fn downgrade(&self) -> WeakUi {
168 WeakUi {
169 inner: Rc::downgrade(&self.inner),
170 executor: Rc::downgrade(&self.executor),
171 services: Rc::downgrade(&self.services),
172 }
173 }
174
175 pub(crate) fn executor(&self) -> &Executor {
178 &self.executor
179 }
180
181 pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
185 self.spawn_in(future, None)
186 }
187
188 pub(crate) fn spawn_in(
189 &self,
190 future: impl std::future::Future<Output = ()> + 'static,
191 owner: Option<mitsuami_reactive::Owner>,
192 ) -> TaskHandle {
193 let id = self.executor.spawn(Box::pin(future), owner);
194 self.changed();
195 TaskHandle::new(id, self.downgrade())
196 }
197
198 pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
200 Sleep::new(self.clone(), duration)
201 }
202
203 pub fn set_clock(&self, clock: Rc<dyn Clock>) {
205 self.executor.set_clock(clock);
206 }
207
208 pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
211 self.executor.set_wake_ui(wake);
212 }
213
214 pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
217 let now = self.executor.now();
218 self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
219 }
220
221 pub fn set_services(&self, services: Box<dyn Services>) {
225 *self.services.borrow_mut() = services;
226 }
227
228 pub fn clipboard_text(&self) -> impl std::future::Future<Output = Option<String>> + use<> {
229 let (reply, text) = reply_future();
230 self.services.borrow_mut().clipboard_text(reply);
231 text
232 }
233
234 pub fn set_clipboard_text(
237 &self,
238 text: &str,
239 ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
240 let (reply, done) = reply_future();
241 self.services.borrow_mut().set_clipboard_text(text, reply);
242 done
243 }
244
245 pub fn alert(&self, parent: Option<NodeId>, alert: Alert) -> impl std::future::Future<Output = usize> + use<> {
247 let (reply, answer) = reply_future();
248 self.services.borrow_mut().alert(parent, &alert, reply);
249 answer
250 }
251
252 pub fn open_file(
254 &self,
255 parent: Option<NodeId>,
256 request: OpenFile,
257 ) -> impl std::future::Future<Output = Option<Vec<std::path::PathBuf>>> + use<> {
258 let (reply, answer) = reply_future();
259 self.services.borrow_mut().open_file(parent, &request, reply);
260 answer
261 }
262
263 pub fn save_file(
264 &self,
265 parent: Option<NodeId>,
266 request: SaveFile,
267 ) -> impl std::future::Future<Output = Option<std::path::PathBuf>> + use<> {
268 let (reply, answer) = reply_future();
269 self.services.borrow_mut().save_file(parent, &request, reply);
270 answer
271 }
272
273 pub fn set_menu(&self, menu: MenuBar) {
276 let (data, handlers) = menu.into_parts();
277 self.inner.borrow_mut().menu_handlers = handlers
278 .into_iter()
279 .map(|(id, handler)| {
280 let handler = crate::task::in_current_scope(move |()| handler());
281 (id, Rc::new(move || handler(())) as Handler0)
282 })
283 .collect();
284 let weak = self.downgrade();
285 let activate: Rc<dyn Fn(u32)> = Rc::new(move |id| {
286 if let Some(ui) = weak.upgrade() {
287 ui.inner.borrow_mut().menu_queue.push_back(id);
288 ui.changed();
289 }
290 });
291 let services = self.services.clone();
292 mitsuami_reactive::effect(move || {
293 let data = data();
294 services.borrow_mut().set_menu(&data, activate.clone());
295 });
296 }
297
298 pub fn pending_tasks(&self) -> usize {
300 self.executor.task_count()
301 }
302
303 pub fn events(&self) -> EventSink {
304 self.inner.borrow().events.clone()
305 }
306
307 pub fn metrics(&self) -> PlatformMetrics {
308 self.inner.borrow().metrics.clone()
309 }
310
311 pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
315 self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
316 }
317
318 fn changed(&self) {
319 let schedule = {
320 let mut inner = self.inner.borrow_mut();
321 if inner.commit_scheduled {
322 return;
323 }
324 inner.commit_scheduled = true;
325 inner.commit_scheduler.clone()
326 };
327 if let Some(schedule) = schedule {
328 schedule();
329 }
330 }
331
332 pub fn create(&self, kind: WidgetKind, props: Vec<Prop>) -> NodeId {
335 let id = {
336 let mut inner = self.inner.borrow_mut();
337 let id = NodeId(inner.next_id);
338 inner.next_id += 1;
339 let taffy = if kind.is_native() {
340 let t = if kind.is_container() {
341 inner.taffy.new_leaf(taffy::Style::default())
342 } else {
343 inner.taffy.new_leaf_with_context(taffy::Style::default(), id)
344 };
345 Some(t.expect("taffy: failed to create node"))
346 } else {
347 None
348 };
349 if kind.is_native() {
350 inner.pending.push(Command::Create { id, kind, props: props.clone() });
351 }
352 inner.nodes.insert(
353 id,
354 Node {
355 kind,
356 parent: None,
357 children: Vec::new(),
358 native_children: Vec::new(),
359 native_parent: None,
360 props,
361 style: Style::default(),
362 a11y: A11yProps::default(),
363 test_id: None,
364 tab_index: None,
365 handlers: Vec::new(),
366 taffy,
367 frame: Rect::ZERO,
368 window_size: Size::ZERO,
369 fit_height: false,
370 scroll_offset: Point::ZERO,
371 },
372 );
373 inner.styles_dirty = true;
374 id
375 };
376 self.changed();
377 id
378 }
379
380 pub fn create_window(&self, title: impl Into<String>, size: impl Into<WindowSize>) -> NodeId {
383 let id = self.create(WidgetKind::Window, vec![Prop::Title(title.into())]);
384 let mut inner = self.inner.borrow_mut();
385 let node = inner.nodes.get_mut(&id).expect("just created");
386 let (size, fit_height) = match size.into() {
387 WindowSize::Fixed(size) => (size, false),
388 WindowSize::FitHeight(width) => (Size::new(width, 0.0), true),
389 };
390 node.window_size = size;
391 node.fit_height = fit_height;
392 node.frame = Rect { origin: Point::ZERO, size };
393 inner.windows.push(id);
394 if !fit_height {
396 inner.pending.push(Command::SetWindowSize { id, size });
397 }
398 id
399 }
400
401 pub fn set_prop(&self, id: NodeId, prop: Prop) {
403 {
404 let mut inner = self.inner.borrow_mut();
405 let inner = &mut *inner;
406 let Some(node) = inner.nodes.get_mut(&id) else { return };
407 if node.prop(&prop) == Some(&prop) {
408 return;
409 }
410 node.props.retain(|p| p.key() != prop.key());
411 node.props.push(prop.clone());
412 if prop.affects_measure()
413 && let Some(t) = node.taffy
414 {
415 let _ = inner.taffy.mark_dirty(t);
416 }
417 if matches!(prop, Prop::TextStyle(_)) {
418 inner.styles_dirty = true;
419 }
420 if node.kind.is_native() {
421 inner.queue_prop(id, prop);
422 }
423 }
424 self.changed();
425 }
426
427 pub fn set_style(&self, id: NodeId, style: Style) {
428 {
429 let mut inner = self.inner.borrow_mut();
430 let Some(node) = inner.nodes.get_mut(&id) else { return };
431 if node.style == style {
432 return;
433 }
434 node.style = style;
435 inner.styles_dirty = true;
436 }
437 self.changed();
438 }
439
440 pub fn update_style(&self, id: NodeId, f: impl FnOnce(&mut Style)) {
442 let style = {
443 let inner = self.inner.borrow();
444 let Some(node) = inner.nodes.get(&id) else { return };
445 let mut style = node.style.clone();
446 f(&mut style);
447 style
448 };
449 self.set_style(id, style);
450 }
451
452 pub fn set_a11y(&self, id: NodeId, a11y: A11yProps) {
453 {
454 let mut inner = self.inner.borrow_mut();
455 let Some(node) = inner.nodes.get_mut(&id) else { return };
456 if node.a11y == a11y {
457 return;
458 }
459 node.a11y = a11y.clone();
460 if node.kind.is_native() {
461 inner.pending.push(Command::SetA11y { id, a11y });
462 }
463 }
464 self.changed();
465 }
466
467 pub fn set_tab_index(&self, id: NodeId, index: Option<u32>) {
470 if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
471 node.tab_index = index;
472 }
473 self.changed();
474 }
475
476 pub fn focused(&self, window: NodeId) -> Option<NodeId> {
478 self.inner.borrow().focused.get(&window).copied()
479 }
480
481 pub fn focus_order(&self, window: NodeId) -> Vec<NodeId> {
484 self.inner.borrow().focus_order(window)
485 }
486
487 pub fn set_test_id(&self, id: NodeId, test_id: impl Into<String>) {
488 if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
489 node.test_id = Some(test_id.into());
490 }
491 }
492
493 pub fn on_event(&self, id: NodeId, handler: impl Fn(&UiEvent) + 'static) {
497 let owner = mitsuami_reactive::Owner::current();
498 let handler = move |event: &UiEvent| match owner {
499 Some(owner) if owner.is_alive() => owner.with(|| handler(event)),
500 _ => handler(event),
501 };
502 if let Some(node) = self.inner.borrow_mut().nodes.get_mut(&id) {
503 node.handlers.push(Rc::new(handler));
504 }
505 }
506
507 pub fn focus(&self, id: NodeId) {
508 self.inner.borrow_mut().pending_focus.push(id);
509 self.changed();
510 }
511
512 pub fn insert_child(&self, parent: NodeId, child: NodeId, index: Option<usize>) {
517 {
518 let mut inner = self.inner.borrow_mut();
519 if !inner.nodes.contains_key(&parent) || !inner.nodes.contains_key(&child) {
520 return;
521 }
522 inner.detach(child);
523 let siblings = &mut inner.nodes.get_mut(&parent).unwrap().children;
524 let index = index.unwrap_or(siblings.len()).min(siblings.len());
525 siblings.insert(index, child);
526 inner.nodes.get_mut(&child).unwrap().parent = Some(parent);
527 inner.mark_resync(parent);
528 inner.styles_dirty = true;
529 }
530 self.changed();
531 }
532
533 pub fn append_child(&self, parent: NodeId, child: NodeId) {
534 self.insert_child(parent, child, None);
535 }
536
537 pub fn set_children(&self, parent: NodeId, children: Vec<NodeId>) {
539 {
540 let mut inner = self.inner.borrow_mut();
541 if !inner.nodes.contains_key(&parent) {
542 return;
543 }
544 let old = inner.nodes[&parent].children.clone();
545 for child in old.iter().filter(|c| !children.contains(c)) {
546 inner.detach(*child);
547 }
548 for child in &children {
549 if inner.nodes.get(child).and_then(|n| n.parent) != Some(parent) {
550 inner.detach(*child);
551 }
552 if let Some(node) = inner.nodes.get_mut(child) {
553 node.parent = Some(parent);
554 }
555 }
556 inner.nodes.get_mut(&parent).unwrap().children = children;
557 inner.mark_resync(parent);
558 inner.styles_dirty = true;
559 }
560 self.changed();
561 }
562
563 pub fn destroy(&self, id: NodeId) {
565 {
566 let mut inner = self.inner.borrow_mut();
567 if !inner.nodes.contains_key(&id) {
568 return;
569 }
570 inner.detach(id);
571 let roots = inner.native_roots(id);
574 for root in &roots {
575 inner.detach_native(*root);
576 }
577 let mut subtree = Vec::new();
578 inner.collect_subtree(id, &mut subtree);
579 for node_id in subtree {
580 let node = inner.nodes.remove(&node_id).expect("in subtree");
581 if let Some(t) = node.taffy {
582 let _ = inner.taffy.remove(t);
583 }
584 inner.resync.remove(&node_id);
585 inner.windows.retain(|w| *w != node_id);
586 inner.focus_orders.remove(&node_id);
587 inner.focused.retain(|window, focused| *window != node_id && *focused != node_id);
588 if node.kind.is_native() {
589 inner.pending.push(Command::Destroy { id: node_id });
590 }
591 }
592 }
593 self.changed();
594 }
595
596 pub fn process_events(&self) {
601 crate::task::with_current(self, || self.dispatch_events());
602 }
603
604 fn dispatch_events(&self) {
605 loop {
606 let chosen = {
607 let mut inner = self.inner.borrow_mut();
608 let id = inner.menu_queue.pop_front();
609 id.and_then(|id| inner.menu_handlers.get(&id).cloned())
610 };
611 if let Some(handler) = chosen {
612 mitsuami_reactive::batch(|| handler());
613 continue;
614 }
615 let next = self.inner.borrow().events.pop();
616 let Some((id, event)) = next else { break };
617 let (handlers, meaning) = {
618 let mut inner = self.inner.borrow_mut();
619 inner.absorb(id, &event);
620 let node = inner.nodes.get(&id);
621 let meaning = match (&event, node.and_then(|n| n.drawn().map(|c| (c, n.frame.size)))) {
623 (UiEvent::Pointer(pointer), Some((custom, size))) => custom.pointer(size, pointer),
624 _ => None,
625 };
626 (node.map(|n| n.handlers.clone()).unwrap_or_default(), meaning)
627 };
628 self.changed();
629 for event in std::iter::once(event).chain(meaning.map(UiEvent::Custom)) {
630 mitsuami_reactive::batch(|| {
631 for handler in &handlers {
632 handler(&event);
633 }
634 });
635 }
636 }
637 }
638
639 pub fn commit(&self) {
641 let mut inner = self.inner.borrow_mut();
642 inner.commit_scheduled = false;
643 if inner.styles_dirty {
644 inner.resolve_styles();
645 }
646 inner.resync_all();
647 inner.sync_focus_orders();
648 for id in std::mem::take(&mut inner.pending_focus) {
649 if inner.nodes.contains_key(&id) {
650 inner.pending.push(Command::Focus { id });
651 }
652 }
653 let batch = std::mem::take(&mut inner.pending);
654 if !batch.is_empty() {
655 inner.backend.apply(&batch);
656 }
657 inner.layout();
658 let frames = std::mem::take(&mut inner.pending);
659 if !frames.is_empty() {
660 inner.backend.apply(&frames);
661 }
662 }
663
664 pub fn tick(&self) {
668 const MAX_TURNS: usize = 64;
669 for _ in 0..MAX_TURNS {
670 self.executor.run_ready(self);
671 self.process_events();
672 self.commit();
673 let idle = {
674 let inner = self.inner.borrow();
675 inner.events.is_empty() && inner.menu_queue.is_empty()
676 };
677 if idle && !self.executor.has_ready() {
678 return;
679 }
680 }
681 }
682
683 pub fn perform(&self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
689 let result = {
690 let mut inner = self.inner.borrow_mut();
691 let result = inner.backend.perform(id, action);
692 match (result, inner.nodes.get(&id).and_then(|n| n.custom())) {
693 (Err(ActionError::Unsupported), Some(custom)) => match custom.action(action) {
694 Some(event) => {
695 inner.events.emit(id, UiEvent::Custom(event));
696 Ok(())
697 }
698 None => Err(ActionError::Unsupported),
699 },
700 (result, _) => result,
701 }
702 };
703 self.process_events();
704 result
705 }
706
707 pub fn synthesize(&self, id: NodeId, input: &crate::backend::SyntheticInput) -> Result<(), ActionError> {
710 let result = self.inner.borrow_mut().backend.synthesize(id, input);
711 self.process_events();
712 result
713 }
714
715 pub fn windows(&self) -> Vec<NodeId> {
718 self.inner.borrow().windows.clone()
719 }
720
721 pub fn exists(&self, id: NodeId) -> bool {
722 self.inner.borrow().nodes.contains_key(&id)
723 }
724
725 pub fn kind(&self, id: NodeId) -> Option<WidgetKind> {
726 self.inner.borrow().nodes.get(&id).map(|n| n.kind)
727 }
728
729 pub fn props(&self, id: NodeId) -> Vec<Prop> {
730 self.inner.borrow().nodes.get(&id).map(|n| n.props.clone()).unwrap_or_default()
731 }
732
733 pub fn parent(&self, id: NodeId) -> Option<NodeId> {
734 self.inner.borrow().nodes.get(&id).and_then(|n| n.parent)
735 }
736
737 pub fn children(&self, id: NodeId) -> Vec<NodeId> {
738 self.inner.borrow().nodes.get(&id).map(|n| n.children.clone()).unwrap_or_default()
739 }
740
741 pub fn native_children(&self, id: NodeId) -> Vec<NodeId> {
742 self.inner.borrow().nodes.get(&id).map(|n| n.native_children.clone()).unwrap_or_default()
743 }
744
745 pub fn frame(&self, id: NodeId) -> Option<Rect> {
747 self.inner.borrow().nodes.get(&id).map(|n| n.frame)
748 }
749
750 pub fn window_frame(&self, id: NodeId) -> Option<Rect> {
752 let inner = self.inner.borrow();
753 let node = inner.nodes.get(&id)?;
754 if node.kind == WidgetKind::Window {
755 return Some(node.frame);
756 }
757 Some(node.frame.offset(inner.window_origin(id)?))
758 }
759
760 pub fn visible_rect(&self, id: NodeId) -> Option<Rect> {
763 let window = self.window_of(id)?;
764 let size = self.window_size(window)?;
765 let mut visible = self.window_frame(id)?.intersection(&Rect::new(0.0, 0.0, size.width, size.height))?;
766 let mut current = self.inner.borrow().nodes.get(&id)?.native_parent;
767 while let Some(ancestor) = current {
768 if self.kind(ancestor) == Some(WidgetKind::ScrollView) {
769 visible = visible.intersection(&self.window_frame(ancestor)?)?;
770 }
771 current = self.inner.borrow().nodes.get(&ancestor)?.native_parent;
772 }
773 Some(visible)
774 }
775
776 pub fn scroll_offset(&self, id: NodeId) -> Option<Point> {
778 let inner = self.inner.borrow();
779 let node = inner.nodes.get(&id)?;
780 (node.kind == WidgetKind::ScrollView).then_some(node.scroll_offset)
781 }
782
783 pub fn scroll_to(&self, id: NodeId, offset: Point) {
785 {
786 let mut inner = self.inner.borrow_mut();
787 let Some(offset) = inner.clamp_scroll(id, offset) else { return };
788 let node = inner.nodes.get_mut(&id).unwrap();
789 if node.scroll_offset == offset {
790 return;
791 }
792 node.scroll_offset = offset;
793 inner.pending.push(Command::ScrollTo { id, offset });
794 }
795 self.changed();
796 }
797
798 pub fn scroll_into_view(&self, id: NodeId) {
800 let mut target = id;
801 loop {
802 let scroll_view = {
803 let inner = self.inner.borrow();
804 let mut current = inner.nodes.get(&target).and_then(|n| n.native_parent);
805 while let Some(ancestor) = current {
806 if inner.nodes[&ancestor].kind == WidgetKind::ScrollView {
807 break;
808 }
809 current = inner.nodes[&ancestor].native_parent;
810 }
811 current
812 };
813 let Some(scroll_view) = scroll_view else { return };
814 let (Some(rect), Some(viewport)) = (self.window_frame(target), self.window_frame(scroll_view)) else {
815 return;
816 };
817 let offset = self.scroll_offset(scroll_view).unwrap_or_default();
818 let x = rect.x() - viewport.x() + offset.x;
820 let y = rect.y() - viewport.y() + offset.y;
821 let fit = |start: f32, len: f32, current: f32, visible: f32| {
822 if start < current {
823 start
824 } else if start + len > current + visible {
825 (start + len - visible).min(start)
826 } else {
827 current
828 }
829 };
830 let next = Point::new(
831 fit(x, rect.width(), offset.x, viewport.width()),
832 fit(y, rect.height(), offset.y, viewport.height()),
833 );
834 self.scroll_to(scroll_view, next);
835 target = scroll_view;
836 }
837 }
838
839 pub fn window_of(&self, id: NodeId) -> Option<NodeId> {
841 self.inner.borrow().window_of(id)
842 }
843
844 pub fn window_size(&self, window: NodeId) -> Option<Size> {
845 self.inner.borrow().nodes.get(&window).map(|n| n.window_size)
846 }
847
848 pub fn native_state(&self, id: NodeId) -> Option<NativeState> {
849 self.inner.borrow().backend.native_state(id)
850 }
851
852 pub fn capture(
854 &self,
855 id: NodeId,
856 ) -> impl std::future::Future<Output = Result<crate::backend::Image, crate::backend::CaptureError>> + use<> {
857 let (reply, image) = reply_future();
858 self.inner.borrow_mut().backend.capture(id, reply);
859 image
860 }
861
862 pub fn inspect(&self, id: NodeId) -> Option<NodeInfo> {
864 let inner = self.inner.borrow();
865 let origin = inner.window_origin(id)?;
866 Some(inner.inspect(id, origin))
867 }
868
869 pub fn a11y_tree(&self, window: NodeId) -> Option<A11yNode> {
871 let inner = self.inner.borrow();
872 let mut nodes = inner.a11y(window, Point::ZERO);
873 (nodes.len() == 1).then(|| nodes.remove(0))
874 }
875}
876
877impl Inner {
878 fn queue_prop(&mut self, id: NodeId, prop: Prop) {
883 let create = self.pending.iter_mut().rev().find_map(|command| match command {
884 Command::Create { id: created, props, .. } if *created == id => Some(props),
885 _ => None,
886 });
887 match create {
888 Some(props) => {
889 props.retain(|p| p.key() != prop.key());
890 props.push(prop);
891 }
892 None => self.pending.push(Command::SetProp { id, prop }),
893 }
894 }
895
896 fn mark_resync(&mut self, id: NodeId) {
897 if let Some(native) = self.native_ancestor_or_self(id) {
898 self.resync.insert(native);
899 }
900 }
901
902 fn native_ancestor_or_self(&self, id: NodeId) -> Option<NodeId> {
903 let mut current = Some(id);
904 while let Some(node_id) = current {
905 let node = self.nodes.get(&node_id)?;
906 if node.kind.is_native() {
907 return Some(node_id);
908 }
909 current = node.parent;
910 }
911 None
912 }
913
914 fn detach(&mut self, child: NodeId) {
915 let Some(parent) = self.nodes.get(&child).and_then(|n| n.parent) else { return };
916 if let Some(node) = self.nodes.get_mut(&parent) {
917 node.children.retain(|c| *c != child);
918 }
919 self.nodes.get_mut(&child).unwrap().parent = None;
920 self.mark_resync(parent);
921 }
922
923 fn detach_native(&mut self, child: NodeId) {
925 let Some(parent) = self.nodes.get(&child).and_then(|n| n.native_parent) else { return };
926 self.pending.push(Command::Remove { parent, child });
927 let child_taffy = self.nodes[&child].taffy;
928 if let Some(node) = self.nodes.get_mut(&parent) {
929 node.native_children.retain(|c| *c != child);
930 if let (Some(p), Some(c)) = (node.taffy, child_taffy) {
931 let _ = self.taffy.remove_child(p, c);
932 }
933 }
934 self.nodes.get_mut(&child).unwrap().native_parent = None;
935 }
936
937 fn native_roots(&self, id: NodeId) -> Vec<NodeId> {
939 let node = &self.nodes[&id];
940 if node.kind.is_native() {
941 return vec![id];
942 }
943 node.children.iter().flat_map(|c| self.native_roots(*c)).collect()
944 }
945
946 fn flattened_children(&self, id: NodeId) -> Vec<NodeId> {
947 self.nodes[&id].children.iter().flat_map(|c| self.native_roots(*c)).collect()
948 }
949
950 fn collect_subtree(&self, id: NodeId, out: &mut Vec<NodeId>) {
951 for child in &self.nodes[&id].children {
952 self.collect_subtree(*child, out);
953 }
954 out.push(id);
955 }
956
957 fn resync_all(&mut self) {
958 let dirty = std::mem::take(&mut self.resync);
959 for id in dirty {
960 if self.nodes.contains_key(&id) {
961 self.resync_node(id);
962 }
963 }
964 }
965
966 fn resync_node(&mut self, parent: NodeId) {
968 let desired = self.flattened_children(parent);
969 let current = self.nodes[&parent].native_children.clone();
970 for child in current.iter().filter(|c| !desired.contains(c)) {
971 self.detach_native(*child);
972 }
973 let mut working: Vec<NodeId> = self.nodes[&parent].native_children.clone();
974 for (index, child) in desired.iter().enumerate() {
975 if working.get(index) == Some(child) {
976 continue;
977 }
978 if let Some(pos) = working.iter().position(|c| c == child) {
979 working.remove(pos);
980 self.pending.push(Command::Remove { parent, child: *child });
981 } else if let Some(other) = self.nodes[child].native_parent
982 && other != parent
983 {
984 self.detach_native(*child);
985 }
986 working.insert(index, *child);
987 self.pending.push(Command::Insert { parent, child: *child, index });
988 }
989 for child in &desired {
990 self.nodes.get_mut(child).unwrap().native_parent = Some(parent);
991 }
992 let taffy_children: Vec<_> = desired.iter().filter_map(|c| self.nodes[c].taffy).collect();
993 if let Some(t) = self.nodes[&parent].taffy {
994 let _ = self.taffy.set_children(t, &taffy_children);
995 }
996 self.nodes.get_mut(&parent).unwrap().native_children = desired;
997 }
998
999 fn focus_order(&self, window: NodeId) -> Vec<NodeId> {
1001 fn walk(inner: &Inner, id: NodeId, out: &mut Vec<(Option<u32>, NodeId)>) {
1002 let node = &inner.nodes[&id];
1003 if node.style.is_hidden() {
1004 return;
1005 }
1006 if matches!(
1007 node.kind,
1008 WidgetKind::Button | WidgetKind::TextInput | WidgetKind::Checkbox | WidgetKind::Switch
1009 ) {
1010 out.push((node.tab_index, id));
1011 }
1012 for child in &node.native_children {
1013 walk(inner, *child, out);
1014 }
1015 }
1016 let mut entries = Vec::new();
1017 if self.nodes.contains_key(&window) {
1018 walk(self, window, &mut entries);
1019 }
1020 entries.sort_by_key(|(index, _)| index.unwrap_or(u32::MAX));
1022 entries.into_iter().map(|(_, id)| id).collect()
1023 }
1024
1025 fn sync_focus_orders(&mut self) {
1026 for window in self.windows.clone() {
1027 let order = self.focus_order(window);
1028 if self.focus_orders.get(&window) != Some(&order) {
1029 self.focus_orders.insert(window, order.clone());
1030 self.pending.push(Command::SetFocusOrder { window, order });
1031 }
1032 }
1033 }
1034
1035 fn resolve_styles(&mut self) {
1036 self.styles_dirty = false;
1037 let body = self.metrics.font_sizes.body;
1038 for window in self.windows.clone() {
1039 let viewport = self.nodes[&window].window_size;
1040 self.resolve_node(window, body, false, viewport, false);
1041 }
1042 }
1043
1044 fn resolve_node(
1047 &mut self,
1048 id: NodeId,
1049 inherited_font: f32,
1050 inherited_rtl: bool,
1051 viewport: Size,
1052 in_stretching_column: bool,
1053 ) {
1054 let node = &self.nodes[&id];
1055 let font_size = match crate::find_prop!(node.props, TextStyle) {
1056 Some(style) => self.metrics.font_sizes.get(style),
1057 None => inherited_font,
1058 };
1059 let rtl = match node.style.direction {
1060 TextDirection::Inherit => inherited_rtl,
1061 TextDirection::Ltr => false,
1062 TextDirection::Rtl => true,
1063 };
1064 if let Some(t) = node.taffy {
1065 let cx = ResolveContext {
1066 font_size,
1067 root_font_size: self.metrics.font_sizes.body,
1068 viewport,
1069 spacing: &self.metrics.spacing,
1070 };
1071 let mut style = node.style.to_taffy(&cx, rtl);
1072 if matches!(node.kind, WidgetKind::Checkbox | WidgetKind::Switch) {
1076 style.justify_self.get_or_insert(taffy::AlignSelf::START);
1077 if in_stretching_column {
1078 style.align_self.get_or_insert(taffy::AlignSelf::START);
1079 }
1080 }
1081 if node.kind == WidgetKind::Window {
1082 style.size = taffy::Size {
1083 width: taffy::Dimension::length(node.window_size.width),
1084 height: if node.fit_height {
1085 taffy::Dimension::auto()
1086 } else {
1087 taffy::Dimension::length(node.window_size.height)
1088 },
1089 };
1090 }
1091 if self.taffy.style(t).ok() != Some(&style) {
1092 let _ = self.taffy.set_style(t, style);
1093 }
1094 }
1095 let in_stretching_column = match node.taffy {
1097 Some(_) => {
1098 let s = &node.style;
1099 s.display == Display::Flex
1100 && matches!(s.flex_direction, FlexDirection::Column | FlexDirection::ColumnReverse)
1101 && matches!(s.align_items, None | Some(Align::Stretch))
1102 }
1103 None => in_stretching_column,
1104 };
1105 for child in self.nodes[&id].children.clone() {
1106 self.resolve_node(child, font_size, rtl, viewport, in_stretching_column);
1107 }
1108 }
1109
1110 fn layout(&mut self) {
1111 for window in self.windows.clone() {
1112 let node = &self.nodes[&window];
1113 let Some(root) = node.taffy else { continue };
1114 let (mut size, fit_height) = (node.window_size, node.fit_height);
1115 let Inner { taffy, backend, nodes, metrics, .. } = self;
1116 let available = taffy::Size {
1117 width: taffy::AvailableSpace::Definite(size.width),
1118 height: if fit_height {
1119 taffy::AvailableSpace::MaxContent
1120 } else {
1121 taffy::AvailableSpace::Definite(size.height)
1122 },
1123 };
1124 let _ = taffy.compute_layout_with_measure(root, available, |input, _, context, style| {
1125 taffy::compute_leaf_layout(
1126 input,
1127 style,
1128 |_, _| 0.0,
1129 |known, available| match context {
1130 Some(id) => {
1131 let request = MeasureRequest {
1132 known_width: known.width,
1133 known_height: known.height,
1134 available_width: space(available.width),
1135 available_height: space(available.height),
1136 };
1137 let size = match nodes.get(id).and_then(|n| n.drawn()) {
1138 Some(custom) => {
1139 let size = custom.measure_drawn(&request, metrics).unwrap_or(Size::ZERO);
1140 Size::new(known.width.unwrap_or(size.width), known.height.unwrap_or(size.height))
1141 }
1142 None => backend.measure(*id, request),
1143 };
1144 taffy::Size { width: size.width, height: size.height }
1145 }
1146 None => taffy::Size::ZERO,
1147 },
1148 )
1149 });
1150 if fit_height {
1151 size.height = self.taffy.layout(root).map_or(0.0, |l| l.size.height).ceil();
1152 let node = self.nodes.get_mut(&window).unwrap();
1153 node.window_size = size;
1154 node.fit_height = false;
1155 self.styles_dirty = true;
1158 self.pending.push(Command::SetWindowSize { id: window, size });
1159 }
1160 self.nodes.get_mut(&window).unwrap().frame = Rect { origin: Point::ZERO, size };
1161 self.collect_frames(window);
1162 }
1163 self.update_drawings();
1164 }
1165
1166 fn update_drawings(&mut self) {
1169 let mut changed = Vec::new();
1170 for (id, node) in &self.nodes {
1171 let Some(drawing) = node.drawn().and_then(|c| c.draw(node.frame.size, &self.metrics)) else { continue };
1172 let drawing = Prop::Drawing(drawing);
1173 if node.prop(&drawing) != Some(&drawing) {
1174 changed.push((*id, drawing));
1175 }
1176 }
1177 for (id, prop) in changed {
1178 let node = self.nodes.get_mut(&id).unwrap();
1179 node.props.retain(|p| p.key() != prop.key());
1180 node.props.push(prop.clone());
1181 self.pending.push(Command::SetProp { id, prop });
1182 }
1183 }
1184
1185 fn collect_frames(&mut self, parent: NodeId) {
1186 for child in self.nodes[&parent].native_children.clone() {
1187 let node = &self.nodes[&child];
1188 if let Some(t) = node.taffy
1189 && let Ok(layout) = self.taffy.layout(t)
1190 {
1191 let frame = Rect::new(layout.location.x, layout.location.y, layout.size.width, layout.size.height);
1192 if frame != node.frame {
1193 self.nodes.get_mut(&child).unwrap().frame = frame;
1194 self.pending.push(Command::SetFrame { id: child, frame });
1195 }
1196 }
1197 self.collect_frames(child);
1198 }
1199 }
1200
1201 fn absorb(&mut self, id: NodeId, event: &UiEvent) {
1204 match event {
1205 UiEvent::Changed(value) => {
1206 let Some(node) = self.nodes.get_mut(&id) else { return };
1207 let prop = match (node.kind, value) {
1208 (WidgetKind::TextInput, EventValue::Text(text)) => Prop::Value(text.clone()),
1209 (WidgetKind::Checkbox | WidgetKind::Switch, EventValue::Bool(b)) => Prop::Checked(*b),
1210 _ => return,
1211 };
1212 node.props.retain(|p| p.key() != prop.key());
1213 node.props.push(prop);
1214 }
1215 UiEvent::FocusIn => {
1216 if let Some(window) = self.window_of(id) {
1217 self.focused.insert(window, id);
1218 }
1219 }
1220 UiEvent::FocusOut => self.focused.retain(|_, focused| *focused != id),
1221 UiEvent::Scrolled(offset) => {
1222 if let Some(node) = self.nodes.get_mut(&id) {
1223 node.scroll_offset = *offset;
1224 }
1225 }
1226 UiEvent::WindowResized(size) => {
1227 if let Some(node) = self.nodes.get_mut(&id) {
1228 node.window_size = *size;
1229 self.styles_dirty = true;
1230 }
1231 }
1232 UiEvent::MetricsChanged => {
1233 self.metrics = self.backend.metrics();
1234 self.styles_dirty = true;
1235 for node in self.nodes.values() {
1236 if let Some(t) = node.taffy {
1237 let _ = self.taffy.mark_dirty(t);
1238 }
1239 }
1240 }
1241 _ => {}
1242 }
1243 }
1244
1245 fn window_of(&self, id: NodeId) -> Option<NodeId> {
1246 let mut current = Some(id);
1247 while let Some(node_id) = current {
1248 let node = self.nodes.get(&node_id)?;
1249 if node.kind == WidgetKind::Window {
1250 return Some(node_id);
1251 }
1252 current = node.parent;
1253 }
1254 None
1255 }
1256
1257 fn content_origin(&self, id: NodeId) -> Point {
1260 let node = &self.nodes[&id];
1261 if node.kind == WidgetKind::Window {
1262 return Point::ZERO;
1263 }
1264 let parent = node.native_parent.map_or(Point::ZERO, |p| self.content_origin(p));
1265 Point::new(
1266 parent.x + node.frame.origin.x - node.scroll_offset.x,
1267 parent.y + node.frame.origin.y - node.scroll_offset.y,
1268 )
1269 }
1270
1271 fn window_origin(&self, id: NodeId) -> Option<Point> {
1273 Some(self.nodes.get(&id)?.native_parent.map_or(Point::ZERO, |p| self.content_origin(p)))
1274 }
1275
1276 fn clamp_scroll(&self, id: NodeId, offset: Point) -> Option<Point> {
1277 let node = self.nodes.get(&id)?;
1278 if node.kind != WidgetKind::ScrollView {
1279 return None;
1280 }
1281 let axes = crate::find_prop!(node.props, ScrollAxes).unwrap_or_default();
1282 let content = node.native_children.first().map_or(Size::ZERO, |c| self.nodes[c].frame.size);
1283 let viewport = node.frame.size;
1284 let clamp = |v: f32, content: f32, viewport: f32, enabled: bool| {
1285 if enabled { v.clamp(0.0, (content - viewport).max(0.0)) } else { 0.0 }
1286 };
1287 Some(Point::new(
1288 clamp(offset.x, content.width, viewport.width, axes.horizontal()),
1289 clamp(offset.y, content.height, viewport.height, axes.vertical()),
1290 ))
1291 }
1292
1293 fn child_origin(node: &Node, frame: Rect) -> Point {
1294 match node.kind {
1295 WidgetKind::Window => Point::ZERO,
1296 _ => Point::new(frame.origin.x - node.scroll_offset.x, frame.origin.y - node.scroll_offset.y),
1297 }
1298 }
1299
1300 fn inspect(&self, id: NodeId, parent_origin: Point) -> NodeInfo {
1301 let node = &self.nodes[&id];
1302 let frame = if node.kind == WidgetKind::Window { node.frame } else { node.frame.offset(parent_origin) };
1303 let origin = Inner::child_origin(node, frame);
1304 NodeInfo {
1305 id,
1306 kind: node.kind,
1307 props: node.props.clone(),
1308 test_id: node.test_id.clone(),
1309 frame,
1310 children: node.native_children.iter().map(|c| self.inspect(*c, origin)).collect(),
1311 }
1312 }
1313
1314 fn text_of(&self, id: NodeId) -> Option<String> {
1315 let node = self.nodes.get(&id)?;
1316 crate::find_prop!(node.props, Text).or_else(|| crate::find_prop!(node.props, Label))
1317 }
1318
1319 fn a11y(&self, id: NodeId, parent_origin: Point) -> Vec<A11yNode> {
1320 let node = &self.nodes[&id];
1321 let a11y = match node.custom() {
1323 Some(custom) => custom.a11y().overridden_by(&node.a11y),
1324 None => node.a11y.clone(),
1325 };
1326 if a11y.hidden || node.style.is_hidden() {
1327 return Vec::new();
1328 }
1329 let frame = if node.kind == WidgetKind::Window { node.frame } else { node.frame.offset(parent_origin) };
1330 let origin = Inner::child_origin(node, frame);
1331 let children: Vec<A11yNode> = node.native_children.iter().flat_map(|c| self.a11y(*c, origin)).collect();
1332
1333 let labelled = a11y.label.is_some() || a11y.labelled_by.is_some();
1334 let role = a11y.role.unwrap_or(match node.kind {
1335 WidgetKind::Window => Role::Window,
1336 WidgetKind::Container if labelled => Role::Group,
1337 WidgetKind::Container | WidgetKind::Fragment => Role::None,
1338 WidgetKind::ScrollView => Role::ScrollArea,
1339 WidgetKind::Text => Role::StaticText,
1340 WidgetKind::Button => Role::Button,
1341 WidgetKind::TextInput => Role::TextField,
1342 WidgetKind::Checkbox => Role::Checkbox,
1343 WidgetKind::Switch => Role::Switch,
1344 WidgetKind::Custom(_) | WidgetKind::Native => Role::Group,
1345 });
1346 if role == Role::None {
1347 return children;
1348 }
1349 let props = &node.props;
1350 let name =
1351 a11y.label.clone().or_else(|| a11y.labelled_by.and_then(|l| self.text_of(l))).or_else(|| match node.kind {
1352 WidgetKind::Window => crate::find_prop!(props, Title),
1353 WidgetKind::Text => crate::find_prop!(props, Text),
1354 WidgetKind::Button | WidgetKind::Checkbox | WidgetKind::Switch => crate::find_prop!(props, Label),
1355 WidgetKind::TextInput => crate::find_prop!(props, Placeholder),
1356 _ => None,
1357 });
1358 vec![A11yNode {
1359 id,
1360 role,
1361 name,
1362 description: a11y.description,
1363 value: match node.kind {
1364 WidgetKind::TextInput => Some(crate::find_prop!(props, Value).unwrap_or_default()),
1365 _ => a11y.value,
1366 },
1367 checked: match node.kind {
1368 WidgetKind::Checkbox | WidgetKind::Switch => Some(crate::find_prop!(props, Checked).unwrap_or(false)),
1369 _ => None,
1370 },
1371 enabled: crate::find_prop!(props, Enabled).unwrap_or(true),
1372 test_id: node.test_id.clone(),
1373 frame,
1374 children,
1375 }]
1376 }
1377}
1378
1379fn space(s: taffy::AvailableSpace) -> AvailableSpace {
1380 match s {
1381 taffy::AvailableSpace::Definite(v) => AvailableSpace::Definite(v),
1382 taffy::AvailableSpace::MinContent => AvailableSpace::MinContent,
1383 taffy::AvailableSpace::MaxContent => AvailableSpace::MaxContent,
1384 }
1385}