1use super::*;
2
3impl Default for SceneTree {
5 fn default() -> Self {
11 let root_style: Style = Style::default()
12 .column()
13 .width(Length::Percent(100.0))
14 .height(Length::Percent(100.0));
15 let root_node: SceneNode = SceneNode::new(1, NodeKind::View, root_style);
16 Self {
17 nodes: vec![root_node],
18 free_list: Vec::new(),
19 live_count: 1,
20 root: NodeId::new(0, 1),
21 focus: FocusManager::default(),
22 revision: 1,
23 transitions: Vec::new(),
24 caret_visible: true,
25 portal_nodes: Vec::new(),
26 dirty_paint_nodes: Vec::new(),
27 full_damage_pending: true,
28 layout_damage_pending: true,
29 full_damage_overflow: false,
30 created_since_damage: 0,
31 extra_logical_damage: Vec::new(),
32 text_selection: None,
33 }
34 }
35}
36
37impl SceneTree {
39 #[must_use]
49 #[inline(always)]
50 pub fn portal_nodes(&self) -> &[NodeId] {
51 let Self { portal_nodes, .. } = self;
52 portal_nodes.as_slice()
53 }
54
55 #[must_use]
65 #[inline(always)]
66 pub fn has_portal_nodes(&self) -> bool {
67 let Self { portal_nodes, .. } = self;
68 !portal_nodes.is_empty()
69 }
70
71 fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
79 let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
80 if is_portal {
81 if !portals.contains(&id) {
82 portals.push(id);
83 }
84 } else if !portals.is_empty() {
85 portals.retain(|existing: &NodeId| *existing != id);
86 }
87 }
88
89 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
101 let is_portal: bool = matches!(kind, NodeKind::Portal)
102 || style.get_layout().get_position() == Position::Fixed;
103 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
104 let slot: &mut SceneNode = &mut self.get_mut_nodes()[index as usize];
105 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
106 *slot = SceneNode::new(next_gen, kind, style);
107 NodeId::new(index, next_gen)
108 } else {
109 let index: u32 = self.get_nodes().len() as u32;
110 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
111 NodeId::new(index, 1)
112 };
113 if is_portal {
114 self.get_mut_portal_nodes().push(id);
115 self.set_full_damage_pending(true);
116 }
117 let next_live: usize = self.get_live_count().saturating_add(1);
118 self.set_live_count(next_live);
119 let next_created: usize = self.get_created_since_damage().saturating_add(1);
120 self.set_created_since_damage(next_created);
121 self.set_layout_damage_pending(true);
122 if next_created > DIRTY_PAINT_FULL_THRESHOLD {
123 self.set_full_damage_pending(true);
124 self.set_full_damage_overflow(true);
125 self.get_mut_dirty_paint_nodes().clear();
126 } else if !self.get_full_damage_pending() {
127 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
128 self.set_full_damage_pending(true);
129 self.set_full_damage_overflow(true);
130 self.get_mut_dirty_paint_nodes().clear();
131 } else {
132 self.get_mut_dirty_paint_nodes().push(id);
133 }
134 }
135 let next_rev: u64 = self.get_revision().wrapping_add(1);
136 self.set_revision(next_rev);
137 id
138 }
139
140 pub fn create_view(&mut self, style: Style) -> NodeId {
151 self.create_node(NodeKind::View, style)
152 }
153
154 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
166 self.create_node(NodeKind::Text(content), style)
167 }
168
169 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
181 self.create_node(NodeKind::Input(state), style)
182 }
183
184 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
196 self.create_node(NodeKind::Image(buffer), style)
197 }
198
199 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
210 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
211 }
212
213 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
225 let id: NodeId = self.create_node(NodeKind::Canvas, style);
226 if let Some(node) = self.get_node_mut(id) {
227 node.set_canvas_painter(Some(painter));
228 }
229 id
230 }
231
232 pub fn create_portal(&mut self, style: Style) -> NodeId {
243 self.create_node(NodeKind::Portal, style)
244 }
245
246 pub fn create_fragment(&mut self) -> NodeId {
256 self.create_node(NodeKind::Fragment, Style::default())
257 }
258
259 #[must_use]
270 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
271 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
272 if node.get_alive() && node.get_generation() == id.get_generation() {
273 Some(node)
274 } else {
275 None
276 }
277 }
278
279 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
290 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
291 if node.get_alive() && node.get_generation() == id.get_generation() {
292 Some(node)
293 } else {
294 None
295 }
296 }
297
298 #[must_use]
308 #[inline(always)]
309 pub fn live_node_count(&self) -> usize {
310 self.get_live_count()
311 }
312
313 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
321 if parent == child {
322 return;
323 }
324 let prev_parent: Option<NodeId> = self.get_node(child).and_then(SceneNode::parent_id);
325 if let Some(old_parent) = prev_parent {
326 if old_parent != parent {
327 self.record_subtree_logical_damage(child);
328 }
329 if let Some(old_node) = self.get_node_mut(old_parent) {
330 old_node
331 .get_mut_children()
332 .retain(|item: &NodeId| *item != child);
333 if old_parent != parent {
334 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
335 }
336 }
337 }
338 if let Some(child_node) = self.get_node_mut(child) {
339 child_node.set_parent(Some(parent));
340 } else {
341 return;
342 }
343 if let Some(parent_node) = self.get_node_mut(parent) {
344 parent_node.get_mut_children().push(child);
345 }
346 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
347 }
348
349 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
357 if children.is_empty() || self.get_node(parent).is_none() {
358 return;
359 }
360 let all_fresh_orphans: bool = children.iter().copied().all(|child: NodeId| {
361 child != parent
362 && self
363 .get_node(child)
364 .is_some_and(|node: &SceneNode| node.parent_id().is_none())
365 });
366 if all_fresh_orphans {
367 for child in children.iter().copied() {
368 if let Some(child_node) = self.get_node_mut(child) {
369 child_node.set_parent(Some(parent));
370 }
371 }
372 if let Some(parent_node) = self.get_node_mut(parent) {
373 parent_node.get_mut_children().extend_from_slice(children);
374 }
375 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
376 return;
377 }
378 let mut attached: Vec<NodeId> = Vec::with_capacity(children.len());
379 for child in children.iter().copied() {
380 if child == parent {
381 continue;
382 }
383 let prev_parent: Option<NodeId> = self
384 .get_node(child)
385 .and_then(|node: &SceneNode| node.parent_id());
386 if let Some(old_parent) = prev_parent {
387 if old_parent != parent {
388 self.record_subtree_logical_damage(child);
389 }
390 if let Some(old_node) = self.get_node_mut(old_parent) {
391 old_node
392 .get_mut_children()
393 .retain(|id: &NodeId| *id != child);
394 }
395 if old_parent != parent {
396 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
397 }
398 }
399 if let Some(child_node) = self.get_node_mut(child) {
400 child_node.set_parent(Some(parent));
401 attached.push(child);
402 }
403 }
404 if attached.is_empty() {
405 return;
406 }
407 if let Some(parent_node) = self.get_node_mut(parent) {
408 parent_node.get_mut_children().extend(attached);
409 }
410 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
411 }
412
413 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
421 let old_children: Vec<NodeId> = match self.get_node_mut(parent) {
422 Some(node) => take(node.get_mut_children()),
423 None => return,
424 };
425 if new_children.is_empty() {
426 for old_child in old_children.into_iter() {
427 self.dispose_subtree(old_child);
428 }
429 } else if old_children.len() > 16 && new_children.len() > 16 {
430 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
431 for old_child in old_children.into_iter() {
432 if !keep_set.contains(&old_child) {
433 self.dispose_subtree(old_child);
434 }
435 }
436 } else {
437 for old_child in old_children.into_iter() {
438 if !new_children.contains(&old_child) {
439 self.dispose_subtree(old_child);
440 }
441 }
442 }
443 for child in new_children.iter().copied() {
444 if let Some(child_node) = self.get_node_mut(child) {
445 child_node.set_parent(Some(parent));
446 }
447 }
448 if let Some(parent_node) = self.get_node_mut(parent) {
449 parent_node.set_children(new_children);
450 }
451 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
452 }
453
454 #[inline]
466 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
467 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
468 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
469 if layout_changed || text_metrics_changed {
470 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
471 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
472 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
473 Some(next_fixed)
474 } else {
475 None
476 };
477 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
478 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
479 let mask: u16 = layout_bits | visual_bits;
480 return (mask, portal_update);
481 }
482 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
483 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
484 if paint_changed || text_visual_changed {
485 (DIRTY_PAINT, None)
486 } else {
487 (DIRTY_NONE, None)
488 }
489 }
490
491 #[inline]
502 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
503 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
504 let transform_changed: bool = prev.get_transform() != next.get_transform();
505 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
506 let focus_removed: bool =
507 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
508 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
509 let a: bool = shadow_changed || transform_changed;
510 let b: bool = border_shrank || focus_removed;
511 let ab: bool = a || b;
512 ab || opacity_toggled_zero
513 }
514
515 pub fn set_style(&mut self, id: NodeId, style: Style) {
523 let pre_snapshot: Option<(u16, Option<bool>, bool, bool)> =
524 self.get_node(id).map(|node: &SceneNode| {
525 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
526 let prev: &Style = node.style_ref();
527 let (mask, update): (u16, Option<bool>) =
528 Self::diff_style_change(prev, &style, is_portal_kind);
529 let pre_paint: bool = mask != DIRTY_NONE
530 && Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
531 let subtree_hidden: bool = pre_paint
532 && (prev.paint_ref().get_opacity() > 0.0)
533 != (style.paint_ref().get_opacity() > 0.0)
534 && !node.get_children().is_empty();
535 (mask, update, pre_paint, subtree_hidden)
536 });
537 let Some((dirty_mask, portal_update, pre_paint, subtree_hidden)) = pre_snapshot else {
538 return;
539 };
540 if dirty_mask == DIRTY_NONE {
541 return;
542 }
543 if subtree_hidden {
544 self.record_subtree_logical_damage(id);
545 } else if pre_paint {
546 self.record_node_logical_damage(id);
547 }
548 let hiding_now: bool = style.layout_ref().get_display() == Display::None
549 || style.paint_ref().get_opacity() <= 0.001
550 || style.paint_ref().get_pointer_events() == PointerEvents::None;
551 if let Some(node) = self.get_node_mut(id) {
552 node.set_style(style);
553 }
554 if hiding_now {
555 self.clear_subtree_hover(id);
556 }
557 if let Some(is_portal) = portal_update {
558 self.sync_portal_registration(id, is_portal);
559 }
560 self.mark_dirty(id, dirty_mask);
561 }
562
563 pub fn mutate_style<F>(&mut self, id: NodeId, mutator: F) -> bool
575 where
576 F: FnOnce(&mut Style),
577 {
578 let prev_opt: Option<(Style, bool, bool)> = self.get_node(id).map(|node: &SceneNode| {
579 (
580 *node.style_ref(),
581 matches!(node.get_kind(), NodeKind::Portal),
582 !node.get_children().is_empty(),
583 )
584 });
585 let Some((prev, is_portal_kind, has_children)) = prev_opt else {
586 return false;
587 };
588 let mut next: Style = prev;
589 mutator(&mut next);
590 let (dirty_mask, portal_update): (u16, Option<bool>) =
591 Self::diff_style_change(&prev, &next, is_portal_kind);
592 if dirty_mask == DIRTY_NONE {
593 return false;
594 }
595 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
596 if pre_paint {
597 let opacity_toggled_zero: bool =
598 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
599 if opacity_toggled_zero && has_children {
600 self.record_subtree_logical_damage(id);
601 } else {
602 self.record_node_logical_damage(id);
603 }
604 }
605 let hiding_now: bool = next.layout_ref().get_display() == Display::None
606 || next.paint_ref().get_opacity() <= 0.001
607 || next.paint_ref().get_pointer_events() == PointerEvents::None;
608 if let Some(node) = self.get_node_mut(id) {
609 node.set_style(next);
610 }
611 if hiding_now {
612 self.clear_subtree_hover(id);
613 }
614 if let Some(is_portal) = portal_update {
615 self.sync_portal_registration(id, is_portal);
616 }
617 self.mark_dirty(id, dirty_mask);
618 true
619 }
620
621 pub fn set_text(&mut self, id: NodeId, text: String) {
629 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
630 Some(node) => {
631 let layout: &LayoutStyle = node.style_ref().layout_ref();
632 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
633 && matches!(layout.get_height(), Length::Px(_));
634 match node.get_mut_kind() {
635 NodeKind::Text(current) => {
636 if *current == text {
637 (false, has_fixed)
638 } else {
639 *current = text;
640 (true, has_fixed)
641 }
642 }
643 _ => (false, false),
644 }
645 }
646 None => (false, false),
647 };
648 if changed {
649 let mask: u16 = if fixed_size {
650 DIRTY_PAINT
651 } else {
652 DIRTY_TEXT_CHANGE_MASK
653 };
654 self.mark_dirty(id, mask);
655 }
656 }
657
658 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
666 let changed: bool = match self.get_node_mut(id) {
667 Some(node) => {
668 let layout_box: LayoutBox = node.get_layout_box();
669 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
670 && layout_box.get_content_size().get_height() <= 0.0
671 && layout_box.get_content_bounds().get_width() <= 0.0
672 && layout_box.get_content_bounds().get_height() <= 0.0;
673 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
674 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
675 } else {
676 let max_x: f32 = (layout_box.get_content_size().get_width()
677 - layout_box.get_content_bounds().get_width())
678 .max(0.0);
679 let max_y: f32 = (layout_box.get_content_size().get_height()
680 - layout_box.get_content_bounds().get_height())
681 .max(0.0);
682 Point::new(
683 offset.get_x().clamp(0.0, max_x),
684 offset.get_y().clamp(0.0, max_y),
685 )
686 };
687 if layout_box.get_scroll_offset() == clamped {
688 false
689 } else {
690 node.get_mut_layout_box().set_scroll_offset(clamped);
691 true
692 }
693 }
694 None => false,
695 };
696 if changed {
697 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
698 }
699 }
700
701 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
710 let changed: bool = match self.get_node_mut(id) {
711 Some(node) => {
712 let next: Option<(f32, f32)> = Some((scroll_y.max(0.0), content_height.max(1.0)));
713 if node.virtual_scroll_metrics() == next {
714 false
715 } else {
716 node.set_virtual_scroll(next);
717 true
718 }
719 }
720 None => false,
721 };
722 if changed {
723 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
724 }
725 }
726
727 #[must_use]
738 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
739 let node: &SceneNode = self.get_node(id)?;
740 let raw: Rect = node.get_layout_box().get_bounds();
741 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
742 self.node_scroll_and_transform(node);
743 Some(Rect::new(
744 raw.get_x() - off.get_x() + tx,
745 raw.get_y() - off.get_y() + ty,
746 raw.get_width() * sx,
747 raw.get_height() * sy,
748 ))
749 }
750
751 #[inline]
762 fn node_scroll_and_transform(&self, node: &SceneNode) -> (Point, f32, f32, f32, f32) {
763 let style: &Style = node.style_ref();
764 let tr: Transform2D = style.get_paint().get_transform();
765 let mut tx: f32 = tr.get_translate_x();
766 let mut ty: f32 = tr.get_translate_y();
767 let sx_scale: f32 = tr.get_scale_x();
768 let sy_scale: f32 = tr.get_scale_y();
769 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
770 || style.get_layout().get_position() == Position::Fixed;
771 let mut scroll_x: f32 = 0.0;
772 let mut scroll_y: f32 = 0.0;
773 let mut cursor: Option<NodeId> = node.parent_id();
774 while let Some(pid) = cursor {
775 if let Some(pnode) = self.get_node(pid) {
776 let pstyle: &Style = pnode.style_ref();
777 let ptr: Transform2D = pstyle.get_paint().get_transform();
778 tx += ptr.get_translate_x();
779 ty += ptr.get_translate_y();
780 if !start_top_layer {
781 let off: Point = pnode.get_layout_box().get_scroll_offset();
782 scroll_x += off.get_x();
783 scroll_y += off.get_y();
784 }
785 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
786 || pstyle.get_layout().get_position() == Position::Fixed;
787 if parent_top_layer {
788 break;
789 }
790 cursor = pnode.parent_id();
791 } else {
792 break;
793 }
794 }
795 (Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale)
796 }
797
798 #[must_use]
811 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
812 let node: &SceneNode = self.get_node(id)?;
813 let raw_bounds: Rect = node.get_layout_box().get_bounds();
814 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
815 return Some(Rect::default());
816 }
817 let style: &Style = node.style_ref();
818 let paint: &PaintStyle = style.paint_ref();
819 let tr: Transform2D = paint.get_transform();
820 if tr.get_rotation_rad().abs() > 0.0001
821 || tr.get_scale_x() <= 0.0
822 || tr.get_scale_y() <= 0.0
823 {
824 return None;
825 }
826 let mut tx: f32 = tr.get_translate_x();
827 let mut ty: f32 = tr.get_translate_y();
828 let sx: f32 = tr.get_scale_x();
829 let sy: f32 = tr.get_scale_y();
830 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
831 || style.layout_ref().get_position() == Position::Fixed;
832 let mut scroll_x: f32 = 0.0;
833 let mut scroll_y: f32 = 0.0;
834 let mut cursor: Option<NodeId> = node.parent_id();
835 while let Some(pid) = cursor {
836 let Some(pnode) = self.get_node(pid) else {
837 break;
838 };
839 let pstyle: &Style = pnode.style_ref();
840 let ptr: Transform2D = pstyle.paint_ref().get_transform();
841 if ptr.get_rotation_rad().abs() > 0.0001
842 || (ptr.get_scale_x() - 1.0).abs() > 0.001
843 || (ptr.get_scale_y() - 1.0).abs() > 0.001
844 {
845 return None;
846 }
847 tx += ptr.get_translate_x();
848 ty += ptr.get_translate_y();
849 if !start_top_layer {
850 let off: Point = pnode.get_layout_box().get_scroll_offset();
851 scroll_x += off.get_x();
852 scroll_y += off.get_y();
853 }
854 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
855 || pstyle.layout_ref().get_position() == Position::Fixed;
856 if parent_top_layer {
857 break;
858 }
859 cursor = pnode.parent_id();
860 }
861 let border_w: f32 = paint.get_border().get_width();
862 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
863 12.0
864 } else {
865 0.0
866 };
867 let mut margin: f32 = 10.0_f32.max(border_w + 6.0).max(focus_pad);
868 if let Some(shadow) = paint.box_shadow() {
869 let blur_pad: f32 = (shadow.get_blur_radius().max(0.5) * 1.5).min(96.0) + 4.0;
870 let spread: f32 = shadow.get_spread_radius().max(0.0);
871 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
872 margin = margin.max(blur_pad + spread + off_max + 4.0);
873 }
874 let base_x: f32 = raw_bounds.get_x() - scroll_x;
875 let base_y: f32 = raw_bounds.get_y() - scroll_y;
876 let base_rect: Rect = Rect::new(
877 base_x - margin,
878 base_y - margin,
879 raw_bounds.get_width() + margin * 2.0,
880 raw_bounds.get_height() + margin * 2.0,
881 );
882 let shifted_x: bool = tx != 0.0 || sx != 1.0;
883 let shifted_y: bool = ty != 0.0 || sy != 1.0;
884 if shifted_x || shifted_y {
885 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
886 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
887 let shifted_rect: Rect = Rect::new(
888 base_x + tx - margin - scale_pad_x,
889 base_y + ty - margin - scale_pad_y,
890 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
891 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
892 );
893 Some(base_rect.union(shifted_rect))
894 } else {
895 Some(base_rect)
896 }
897 }
898
899 #[must_use]
910 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
911 let x0: f32 = (logical.get_x() * scale).floor();
912 let y0: f32 = (logical.get_y() * scale).floor();
913 let x1: f32 = (logical.right() * scale).ceil();
914 let y1: f32 = (logical.bottom() * scale).ceil();
915 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
916 }
917
918 fn record_node_logical_damage(&mut self, id: NodeId) {
925 if self.get_full_damage_pending() {
926 return;
927 }
928 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
929 match rect_opt {
930 Some(rect) => {
931 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
932 return;
933 }
934 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
935 self.set_full_damage_pending(true);
936 self.set_full_damage_overflow(true);
937 self.get_mut_extra_logical_damage().clear();
938 } else {
939 self.get_mut_extra_logical_damage().push(rect);
940 }
941 }
942 None => {
943 self.set_full_damage_pending(true);
944 }
945 }
946 }
947
948 fn record_subtree_logical_damage(&mut self, root: NodeId) {
955 if self.get_full_damage_pending() {
956 return;
957 }
958 let mut stack: Vec<NodeId> = vec![root];
959 let mut visited: usize = 0;
960 while let Some(current) = stack.pop() {
961 let Some(node) = self.get_node(current) else {
962 continue;
963 };
964 visited += 1;
965 if visited > DIRTY_PAINT_FULL_THRESHOLD {
966 self.set_full_damage_pending(true);
967 self.set_full_damage_overflow(true);
968 self.get_mut_extra_logical_damage().clear();
969 return;
970 }
971 let children: Vec<NodeId> = node.get_children().clone();
972 let raw_bounds: Rect = node.get_layout_box().get_bounds();
973 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
974 self.record_node_logical_damage(current);
975 if self.get_full_damage_pending() {
976 return;
977 }
978 }
979 for child in children.into_iter() {
980 stack.push(child);
981 }
982 }
983 }
984
985 pub fn start_transition(&mut self, mut transition: NodeTransition) {
992 let target: NodeId = transition.get_node();
993 let had_active: bool = self
994 .get_transitions()
995 .iter()
996 .any(|tr: &NodeTransition| tr.get_node() == target);
997 self.get_mut_transitions()
998 .retain(|tr: &NodeTransition| tr.get_node() != target);
999 if had_active && let Some(node) = self.get_node(target) {
1000 let paint: PaintStyle = node.get_style().get_paint();
1001 let tr: Transform2D = paint.get_transform();
1002 let cur_op: f32 = paint.get_opacity();
1003 let cur_tx: f32 = tr.get_translate_x();
1004 let cur_ty: f32 = tr.get_translate_y();
1005 let cur_sc: f32 = tr.get_scale_x();
1006 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
1007 .hypot(transition.get_to_ty() - transition.get_from_ty())
1008 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
1009 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
1010 .hypot(transition.get_to_ty() - cur_ty)
1011 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
1012 if full_dist > 0.01 {
1013 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
1014 transition.set_duration((transition.get_duration() * ratio).max(0.05));
1015 }
1016 transition.set_from_opacity(cur_op);
1017 transition.set_from_tx(cur_tx);
1018 transition.set_from_ty(cur_ty);
1019 transition.set_from_scale(cur_sc);
1020 }
1021 let (opacity, transform): (f32, Transform2D) = transition.sample();
1022 let mut unhidden: bool = false;
1023 if let Some(node) = self.get_node_mut(target) {
1024 let style: &mut Style = node.get_mut_style();
1025 if !transition.get_hide_on_complete()
1026 && style.layout_ref().get_display() == Display::None
1027 {
1028 style.get_mut_layout().set_display(Display::Flex);
1029 unhidden = true;
1030 }
1031 style.get_mut_paint().set_opacity(opacity);
1032 style.get_mut_paint().set_transform(transform);
1033 }
1034 if unhidden {
1035 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1036 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1037 } else {
1038 self.mark_dirty(target, DIRTY_PAINT);
1039 }
1040 self.get_mut_transitions().push(transition);
1041 }
1042
1043 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
1054 let len: usize = self.get_transitions().len();
1055 if len == 0 {
1056 return false;
1057 }
1058 let step: f32 = dt_secs.clamp(0.001, 0.05);
1059 let mut any_updated: bool = false;
1060 let mut write_idx: usize = 0;
1061 for read_idx in 0..len {
1062 let target: NodeId = self.get_transitions()[read_idx].get_node();
1063 if self.get_node(target).is_none() {
1064 continue;
1065 }
1066 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
1067 let tr: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
1068 let total_span: f32 = tr.get_delay() + tr.get_duration();
1069 let prev_elapsed: f32 = tr.get_elapsed();
1070 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
1071 tr.set_elapsed(next_elapsed);
1072 let is_done: bool = tr.is_complete();
1073 let in_hold: bool =
1074 prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !is_done;
1075 if in_hold {
1076 (is_done, None, false)
1077 } else {
1078 let sampled: (f32, Transform2D) = tr.sample();
1079 let should_hide: bool = is_done && tr.get_hide_on_complete();
1080 (is_done, Some(sampled), should_hide)
1081 }
1082 };
1083 if let Some((opacity, transform)) = sample_opt {
1084 if let Some(node) = self.get_node_mut(target) {
1085 let style: &mut Style = node.get_mut_style();
1086 style.get_mut_paint().set_opacity(opacity);
1087 style.get_mut_paint().set_transform(transform);
1088 if hide {
1089 style.get_mut_layout().set_display(Display::None);
1090 }
1091 }
1092 if hide {
1093 self.clear_subtree_hover(target);
1094 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1095 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1096 } else {
1097 self.mark_dirty(target, DIRTY_PAINT);
1098 }
1099 any_updated = true;
1100 }
1101 if !done {
1102 if write_idx != read_idx {
1103 self.get_mut_transitions().swap(write_idx, read_idx);
1104 }
1105 write_idx += 1;
1106 }
1107 }
1108 self.get_mut_transitions().truncate(write_idx);
1109 any_updated
1110 }
1111
1112 fn clear_subtree_hover(&mut self, root: NodeId) {
1119 let mut stack: Vec<NodeId> = vec![root];
1120 while let Some(id) = stack.pop() {
1121 if self.get_focus().hovered_node() == Some(id) {
1122 self.get_mut_focus().set_hovered(None);
1123 }
1124 if self.get_focus().pressed_node() == Some(id) {
1125 self.get_mut_focus().set_pressed(None);
1126 }
1127 if self.get_focus().focused_node() == Some(id) {
1128 self.get_mut_focus().set_focused(None);
1129 }
1130 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(id) {
1131 Some(node) => {
1132 node.get_mut_interaction().set_hovered(false);
1133 node.get_mut_interaction().set_pressed(false);
1134 node.get_mut_interaction().set_focused(false);
1135 if node.get_children().is_empty() {
1136 None
1137 } else {
1138 Some(node.get_children().clone())
1139 }
1140 }
1141 None => continue,
1142 };
1143 if let Some(children) = children_opt {
1144 stack.extend(children);
1145 }
1146 }
1147 }
1148
1149 #[must_use]
1159 pub fn has_active_transitions(&self) -> bool {
1160 !self.get_transitions().is_empty()
1161 }
1162
1163 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
1171 if let Some(node) = self.get_node_mut(id) {
1172 node.add_lifecycle(hook);
1173 }
1174 }
1175
1176 #[must_use]
1187 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1188 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1189 let mut stack: Vec<NodeId> = vec![root];
1190 while let Some(current) = stack.pop() {
1191 if let Some(node) = self.get_node(current) {
1192 for hook in node.lifecycle_observers().into_iter() {
1193 out.push((current, hook));
1194 }
1195 for child in node.get_children().iter().rev().copied() {
1196 stack.push(child);
1197 }
1198 }
1199 }
1200 out
1201 }
1202
1203 #[must_use]
1213 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1214 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1215 let mut stack: Vec<NodeId> = vec![self.get_root()];
1216 while let Some(current) = stack.pop() {
1217 if let Some(node) = self.get_node(current) {
1218 if node.style_ref().layout_ref().get_display() == Display::None {
1219 continue;
1220 }
1221 for hook in node.lifecycle_observers().into_iter() {
1222 out.push((current, hook));
1223 }
1224 for child in node.get_children().iter().rev().copied() {
1225 stack.push(child);
1226 }
1227 }
1228 }
1229 out
1230 }
1231
1232 #[must_use]
1243 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
1244 let mut out: Vec<ScopeId> = Vec::new();
1245 let mut stack: Vec<NodeId> = vec![root];
1246 while let Some(current) = stack.pop() {
1247 if let Some(node) = self.get_node(current) {
1248 if let Some(scope) = node.owned_scope() {
1249 out.push(scope.id());
1250 }
1251 for child in node.get_children().iter().rev().copied() {
1252 stack.push(child);
1253 }
1254 }
1255 }
1256 out
1257 }
1258
1259 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
1266 if self.get_transitions().is_empty() {
1267 return;
1268 }
1269 let mut ids: HashSet<NodeId> = HashSet::new();
1270 let mut stack: Vec<NodeId> = vec![root];
1271 while let Some(current) = stack.pop() {
1272 if ids.insert(current)
1273 && let Some(node) = self.get_node(current)
1274 {
1275 for child in node.get_children().iter().copied() {
1276 stack.push(child);
1277 }
1278 }
1279 }
1280 self.get_mut_transitions()
1281 .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
1282 }
1283
1284 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
1292 if let Some(node) = self.get_node_mut(id) {
1293 if let Some(existing) = node.owned_scope() {
1294 existing.enter(|| {
1295 on_cleanup(move || {
1296 scope.dispose();
1297 });
1298 });
1299 } else {
1300 node.set_scope(Some(scope));
1301 }
1302 }
1303 }
1304
1305 pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
1313 let check_portal: bool = (mask & DIRTY_LAYOUT) != 0;
1314 let (prev_bits, mut parent_opt, portal_state): (u16, Option<NodeId>, Option<bool>) =
1315 match self.get_node_mut(id) {
1316 Some(node) => {
1317 let prev: u16 = node.get_dirty().get_bits();
1318 node.get_mut_dirty().insert(mask);
1319 let portal_opt: Option<bool> = if check_portal {
1320 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
1321 || node.style_ref().get_layout().get_position() == Position::Fixed;
1322 Some(is_portal)
1323 } else {
1324 None
1325 };
1326 (prev, node.parent_id(), portal_opt)
1327 }
1328 None => return,
1329 };
1330 if let Some(is_portal) = portal_state
1331 && (is_portal || self.has_portal_nodes())
1332 {
1333 self.sync_portal_registration(id, is_portal);
1334 }
1335 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
1336 self.set_layout_damage_pending(true);
1337 }
1338 let paint_or_scroll: u16 = DIRTY_PAINT | DIRTY_SCROLL;
1339 if !self.get_full_damage_pending()
1340 && (mask & paint_or_scroll) != 0
1341 && (prev_bits & paint_or_scroll) == 0
1342 {
1343 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1344 self.set_full_damage_pending(true);
1345 self.set_full_damage_overflow(true);
1346 self.get_mut_dirty_paint_nodes().clear();
1347 } else {
1348 self.get_mut_dirty_paint_nodes().push(id);
1349 }
1350 }
1351 let mut ancestor_mask: u16 = DIRTY_NONE;
1352 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
1353 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
1354 }
1355 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
1356 ancestor_mask |= DIRTY_SUBTREE_PAINT;
1357 }
1358 while let Some(ancestor_id) = parent_opt {
1359 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1360 let already: bool =
1361 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
1362 ancestor.get_mut_dirty().insert(ancestor_mask);
1363 if already {
1364 break;
1365 }
1366 parent_opt = ancestor.parent_id();
1367 } else {
1368 break;
1369 }
1370 }
1371 let next_rev: u64 = self.get_revision().wrapping_add(1);
1372 self.set_revision(next_rev);
1373 }
1374
1375 #[must_use]
1386 pub fn is_node_visible(&self, id: NodeId) -> bool {
1387 let root: NodeId = self.get_root();
1388 let mut cursor: Option<NodeId> = Some(id);
1389 while let Some(cur) = cursor {
1390 let Some(node) = self.get_node(cur) else {
1391 return false;
1392 };
1393 let style: &Style = node.style_ref();
1394 if style.get_layout().get_display() == Display::None
1395 || style.get_paint().get_opacity() <= 0.001
1396 {
1397 return false;
1398 }
1399 if cur == root {
1400 return true;
1401 }
1402 cursor = node.parent_id();
1403 }
1404 false
1405 }
1406
1407 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
1418 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
1419 damage
1420 }
1421
1422 pub(crate) fn collect_surgical_paint_damage(
1434 &mut self,
1435 scale: f32,
1436 allow_partial_layout: bool,
1437 ) -> (DamageRegion, bool) {
1438 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
1439 let layout_pending: bool = self.get_layout_damage_pending();
1440 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
1441 let no_extra: bool = self.get_extra_logical_damage().is_empty();
1442 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
1443 self.set_created_since_damage(0);
1444 return (DamageRegion::default(), false);
1445 }
1446 let mut full: bool =
1447 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
1448 let mut region: DamageRegion = DamageRegion::default();
1449 if !full {
1450 let extra_len: usize = self.get_extra_logical_damage().len();
1451 for i in 0..extra_len {
1452 let logical_rect: Rect = self.get_extra_logical_damage()[i];
1453 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
1454 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1455 }
1456 }
1457 let dirty_len: usize = self.get_dirty_paint_nodes().len();
1458 for i in 0..dirty_len {
1459 let nid: NodeId = self.get_dirty_paint_nodes()[i];
1460 let Some(node) = self.get_node(nid) else {
1461 continue;
1462 };
1463 let bits: u16 = node.get_dirty().get_bits();
1464 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
1465 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
1466 full = true;
1467 break;
1468 }
1469 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
1470 full = true;
1471 break;
1472 }
1473 if (bits & (DIRTY_PAINT | DIRTY_SCROLL)) == 0 {
1474 continue;
1475 }
1476 let raw_bounds: Rect = node.get_layout_box().get_bounds();
1477 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
1478 match self.node_conservative_logical_rect(nid) {
1479 Some(logical_rect) => {
1480 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1481 }
1482 None => {
1483 full = true;
1484 break;
1485 }
1486 }
1487 } else if (bits & DIRTY_PAINT) != 0
1488 && !has_layout_bits
1489 && node.style_ref().layout_ref().get_display() != Display::None
1490 {
1491 full = true;
1492 break;
1493 }
1494 }
1495 }
1496 self.set_layout_damage_pending(false);
1497 self.set_created_since_damage(0);
1498 self.get_mut_extra_logical_damage().clear();
1499 if !full {
1500 let dirty_len: usize = self.get_dirty_paint_nodes().len();
1501 for i in 0..dirty_len {
1502 let nid: NodeId = self.get_dirty_paint_nodes()[i];
1503 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
1504 Some(node) => {
1505 node.get_mut_dirty().remove(clear_mask);
1506 node.parent_id()
1507 }
1508 None => None,
1509 };
1510 while let Some(ancestor_id) = parent_opt {
1511 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1512 if (ancestor.get_dirty().get_bits() & DIRTY_SUBTREE_PAINT) == 0 {
1513 break;
1514 }
1515 ancestor.get_mut_dirty().remove(DIRTY_SUBTREE_PAINT);
1516 parent_opt = ancestor.parent_id();
1517 } else {
1518 break;
1519 }
1520 }
1521 }
1522 self.get_mut_dirty_paint_nodes().clear();
1523 return (region, layout_pending);
1524 }
1525 self.set_full_damage_pending(false);
1526 self.get_mut_dirty_paint_nodes().clear();
1527 for node in self.get_mut_nodes().iter_mut() {
1528 if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
1529 node.get_mut_dirty().remove(clear_mask);
1530 }
1531 }
1532 (DamageRegion::full(), layout_pending)
1533 }
1534
1535 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
1545 let was_overflow: bool = self.get_full_damage_overflow();
1546 self.set_full_damage_overflow(false);
1547 was_overflow
1548 }
1549
1550 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
1561 if id == self.get_root() {
1562 return (Vec::new(), Vec::new());
1563 }
1564 self.record_subtree_logical_damage(id);
1565 self.cancel_subtree_transitions(id);
1566 let mut stack: Vec<NodeId> = vec![id];
1567 let mut scopes: Vec<Scope> = Vec::new();
1568 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1569 while let Some(current) = stack.pop() {
1570 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
1571 Some(node) => {
1572 node.set_alive(false);
1573 if node.has_extras() {
1574 if let Some(scope) = node.owned_scope() {
1575 scopes.push(scope);
1576 }
1577 for hook in node.take_lifecycles().into_iter() {
1578 observers.push((current, hook));
1579 }
1580 node.clear_extras();
1581 }
1582 node.set_parent(None);
1583 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
1584 node.set_generation(next_gen);
1585 Some(take(node.get_mut_children()))
1586 }
1587 None => None,
1588 };
1589 let Some(children) = children_opt else {
1590 continue;
1591 };
1592 let next_live: usize = self.get_live_count().saturating_sub(1);
1593 self.set_live_count(next_live);
1594 if !self.portal_nodes().is_empty() {
1595 self.sync_portal_registration(current, false);
1596 }
1597 if self.get_focus().focused_node() == Some(current) {
1598 self.get_mut_focus().set_focused(None);
1599 }
1600 if self.get_focus().hovered_node() == Some(current) {
1601 self.get_mut_focus().set_hovered(None);
1602 }
1603 if self.get_focus().pressed_node() == Some(current) {
1604 self.get_mut_focus().set_pressed(None);
1605 }
1606 if self
1607 .text_selection()
1608 .map(|sel: SelectionState| sel.get_node_id())
1609 == Some(current)
1610 {
1611 self.set_text_selection(None);
1612 }
1613 self.get_mut_free_list().push(current.get_index());
1614 for child in children.into_iter() {
1615 stack.push(child);
1616 }
1617 }
1618 (scopes, observers)
1619 }
1620
1621 pub fn dispose_subtree(&mut self, id: NodeId) {
1628 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
1629 finalize_disposed_subtree(scopes, observers);
1630 }
1631
1632 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
1643 let prev: Option<NodeId> = self.get_focus().focused_node();
1644 if prev == target {
1645 return Vec::new();
1646 }
1647 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
1648 if let Some(old_id) = prev {
1649 if let Some(old_node) = self.get_node_mut(old_id) {
1650 old_node.get_mut_interaction().set_focused(false);
1651 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
1652 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
1653 }
1654 }
1655 self.mark_dirty(old_id, DIRTY_PAINT);
1656 }
1657 self.get_mut_focus().set_focused(target);
1658 if let Some(new_id) = target {
1659 if let Some(new_node) = self.get_node_mut(new_id) {
1660 new_node.get_mut_interaction().set_focused(true);
1661 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
1662 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
1663 }
1664 }
1665 self.mark_dirty(new_id, DIRTY_PAINT);
1666 }
1667 callbacks
1668 }
1669
1670 #[must_use]
1681 pub fn is_node_selectable(&self, id: NodeId) -> bool {
1682 let mut cursor: Option<NodeId> = Some(id);
1683 while let Some(cur) = cursor {
1684 let Some(node) = self.get_node(cur) else {
1685 return false;
1686 };
1687 let text_style: &TextStyle = node.style_ref().text_ref();
1688 if text_style.get_selectable() {
1689 return true;
1690 }
1691 if text_style.get_selectable_explicit() {
1692 return false;
1693 }
1694 cursor = node.parent_id();
1695 }
1696 false
1697 }
1698
1699 #[must_use]
1710 pub fn effective_selection_color(&self, id: NodeId) -> Color {
1711 let mut cursor: Option<NodeId> = Some(id);
1712 while let Some(cur) = cursor {
1713 let Some(node) = self.get_node(cur) else {
1714 break;
1715 };
1716 if let Some(color) = node.style_ref().text_ref().selection_color() {
1717 return color;
1718 }
1719 cursor = node.parent_id();
1720 }
1721 DEFAULT_TEXT_SELECTION_COLOR
1722 }
1723
1724 #[must_use]
1734 pub fn text_selection(&self) -> Option<SelectionState> {
1735 let Self { text_selection, .. } = self;
1736 *text_selection
1737 }
1738
1739 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
1746 let prev: Option<SelectionState> = self.text_selection();
1747 if prev == selection {
1748 return;
1749 }
1750 let Self { text_selection, .. } = self;
1751 *text_selection = selection;
1752 if let Some(old_sel) = prev {
1753 self.mark_dirty(old_sel.get_node_id(), DIRTY_PAINT);
1754 }
1755 if let Some(new_sel) = selection {
1756 self.mark_dirty(new_sel.get_node_id(), DIRTY_PAINT);
1757 }
1758 }
1759
1760 pub fn clear_text_selection(&mut self) {
1766 self.set_text_selection(None);
1767 }
1768
1769 #[must_use]
1779 pub fn get_selected_text(&self) -> Option<String> {
1780 let sel: SelectionState = self.text_selection()?;
1781 if sel.is_empty() {
1782 return None;
1783 }
1784 let node: &SceneNode = self.get_node(sel.get_node_id())?;
1785 let NodeKind::Text(content) = node.get_kind() else {
1786 return None;
1787 };
1788 let extracted: &str = sel.extract_from(content.as_str());
1789 if extracted.is_empty() {
1790 None
1791 } else {
1792 Some(extracted.to_string())
1793 }
1794 }
1795
1796 pub fn select_all_text(&mut self, id: NodeId) -> bool {
1807 if !self.is_node_selectable(id) {
1808 return false;
1809 }
1810 let char_len: Option<usize> = self.get_node(id).and_then(|node: &SceneNode| {
1811 if let NodeKind::Text(content) = node.get_kind() {
1812 Some(content.chars().count())
1813 } else {
1814 None
1815 }
1816 });
1817 let Some(len) = char_len else {
1818 return false;
1819 };
1820 if len == 0 {
1821 return false;
1822 }
1823 self.set_text_selection(Some(SelectionState::new(id, 0, len)));
1824 true
1825 }
1826}
1827
1828impl SceneHandle {
1830 #[must_use]
1836 pub fn new_tree() -> Self {
1837 Self {
1838 inner: Rc::new(RefCell::new(SceneTree::default())),
1839 }
1840 }
1841
1842 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
1851 self.with_write(
1852 |tree: &mut SceneTree| {
1853 tree.set_virtual_scroll(id, scroll_y, content_height);
1854 },
1855 (),
1856 );
1857 }
1858
1859 #[must_use]
1870 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
1871 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
1872 }
1873
1874 pub fn start_transition(&self, transition: NodeTransition) {
1881 self.with_write(
1882 |tree: &mut SceneTree| {
1883 tree.start_transition(transition);
1884 },
1885 (),
1886 );
1887 }
1888
1889 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
1897 self.with_write(
1898 |tree: &mut SceneTree| {
1899 tree.mark_dirty(id, mask);
1900 },
1901 (),
1902 );
1903 }
1904
1905 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
1913 let (scopes, observers): DisposedSubtreePayload = self.with_write(
1914 |tree: &mut SceneTree| {
1915 let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
1916 Some(node) => take(node.get_mut_children()),
1917 None => return (Vec::new(), Vec::new()),
1918 };
1919 let mut all_scopes: Vec<Scope> = Vec::new();
1920 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1921 if new_children.is_empty() {
1922 for old_child in old_children.into_iter() {
1923 let (sc, ob): DisposedSubtreePayload =
1924 tree.dispose_subtree_collect(old_child);
1925 all_scopes.extend(sc);
1926 all_obs.extend(ob);
1927 }
1928 } else if old_children.len() > 16 && new_children.len() > 16 {
1929 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1930 for old_child in old_children.into_iter() {
1931 if !keep_set.contains(&old_child) {
1932 let (sc, ob): DisposedSubtreePayload =
1933 tree.dispose_subtree_collect(old_child);
1934 all_scopes.extend(sc);
1935 all_obs.extend(ob);
1936 }
1937 }
1938 } else {
1939 for old_child in old_children.into_iter() {
1940 if !new_children.contains(&old_child) {
1941 let (sc, ob): DisposedSubtreePayload =
1942 tree.dispose_subtree_collect(old_child);
1943 all_scopes.extend(sc);
1944 all_obs.extend(ob);
1945 }
1946 }
1947 }
1948 for child in new_children.iter().copied() {
1949 if let Some(child_node) = tree.get_node_mut(child) {
1950 child_node.set_parent(Some(parent));
1951 }
1952 }
1953 if let Some(parent_node) = tree.get_node_mut(parent) {
1954 parent_node.set_children(new_children);
1955 }
1956 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1957 (all_scopes, all_obs)
1958 },
1959 (Vec::new(), Vec::new()),
1960 );
1961 finalize_disposed_subtree(scopes, observers);
1962 }
1963
1964 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
1972 let (scopes, observers): DisposedSubtreePayload = self.with_write(
1973 |tree: &mut SceneTree| {
1974 if let Some(pnode) = tree.get_node_mut(parent) {
1975 pnode.get_mut_children().retain(|id: &NodeId| *id != child);
1976 }
1977 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
1978 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1979 out
1980 },
1981 (Vec::new(), Vec::new()),
1982 );
1983 finalize_disposed_subtree(scopes, observers);
1984 }
1985
1986 pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
1998 where
1999 F: FnOnce(&mut Style),
2000 {
2001 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
2002 }
2003
2004 pub fn freeze_subtree(&self, root: NodeId) {
2011 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2012 |tree: &mut SceneTree| {
2013 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
2014 tree.cancel_subtree_transitions(root);
2015 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
2016 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
2017 if layout.get_display() == Display::None {
2018 false
2019 } else {
2020 layout.set_display(Display::None);
2021 true
2022 }
2023 } else {
2024 false
2025 };
2026 if changed {
2027 tree.clear_subtree_hover(root);
2028 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2029 }
2030 obs
2031 },
2032 Vec::new(),
2033 );
2034 dispatch_lifecycle_freeze(&observers);
2035 }
2036
2037 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
2045 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2046 |tree: &mut SceneTree| {
2047 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
2048 tree.cancel_subtree_transitions(root);
2049 let mut demoted_fixed: bool = false;
2050 if let Some(node) = tree.get_node_mut(root) {
2051 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
2052 let st: &mut Style = node.get_mut_style();
2053 demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
2054 st.get_mut_layout()
2055 .set_position(Position::Absolute)
2056 .set_top(Some(0.0))
2057 .set_right(Some(0.0))
2058 .set_bottom(None)
2059 .set_left(Some(0.0))
2060 .set_z_index(0);
2061 st.get_mut_paint().set_pointer_events(PointerEvents::None);
2062 }
2063 tree.clear_subtree_hover(root);
2064 if demoted_fixed {
2065 tree.sync_portal_registration(root, false);
2066 }
2067 tree.start_transition(exit_transition.with_hide_on_complete(true));
2068 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2069 obs
2070 },
2071 Vec::new(),
2072 );
2073 dispatch_lifecycle_freeze(&observers);
2074 }
2075
2076 pub fn resume_subtree(&self, root: NodeId) {
2083 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2084 |tree: &mut SceneTree| {
2085 let mut unhidden: bool = false;
2086 if let Some(node) = tree.get_node_mut(root) {
2087 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
2088 if layout.get_display() == Display::None {
2089 layout.set_display(Display::Flex);
2090 unhidden = true;
2091 }
2092 }
2093 if unhidden {
2094 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2095 } else {
2096 tree.mark_dirty(root, DIRTY_PAINT);
2097 }
2098 tree.collect_subtree_lifecycles(root)
2099 },
2100 Vec::new(),
2101 );
2102 dispatch_lifecycle_resume(&observers);
2103 }
2104
2105 pub fn activate_subtree(&self, root: NodeId) {
2112 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2113 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2114 Vec::new(),
2115 );
2116 dispatch_lifecycle_activate(&observers);
2117 }
2118
2119 pub fn update_subtree(&self, root: NodeId) {
2126 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2127 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2128 Vec::new(),
2129 );
2130 dispatch_lifecycle_update(&observers);
2131 }
2132
2133 pub fn emit_subtree_appear(&self, root: NodeId) {
2140 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2141 |tree: &SceneTree| {
2142 (
2143 tree.collect_subtree_lifecycles(root),
2144 tree.collect_subtree_scope_ids(root),
2145 )
2146 },
2147 (Vec::new(), Vec::new()),
2148 );
2149 let ev: SystemEvent = SystemEvent::Appear;
2150 dispatch_lifecycle_system_event(&observers, &ev);
2151 dispatch_system_event_to_scopes(&scopes, &ev);
2152 }
2153
2154 pub fn emit_subtree_disappear(&self, root: NodeId) {
2161 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2162 |tree: &SceneTree| {
2163 (
2164 tree.collect_subtree_lifecycles(root),
2165 tree.collect_subtree_scope_ids(root),
2166 )
2167 },
2168 (Vec::new(), Vec::new()),
2169 );
2170 let ev: SystemEvent = SystemEvent::Disappear;
2171 dispatch_lifecycle_system_event(&observers, &ev);
2172 dispatch_system_event_to_scopes(&scopes, &ev);
2173 }
2174
2175 #[must_use]
2185 pub fn has_active_transitions(&self) -> bool {
2186 self.with_read(SceneTree::has_active_transitions, false)
2187 }
2188
2189 #[must_use]
2199 pub fn get_selected_text(&self) -> Option<String> {
2200 self.with_read(SceneTree::get_selected_text, None)
2201 }
2202
2203 pub fn clear_text_selection(&self) {
2209 self.with_write(SceneTree::clear_text_selection, ());
2210 }
2211
2212 pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
2224 where
2225 F: FnOnce(&SceneTree) -> R,
2226 {
2227 let Self { inner } = self;
2228 match inner.try_borrow() {
2229 Ok(guard) => operation(&guard),
2230 Err(_) => fallback,
2231 }
2232 }
2233
2234 pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
2246 where
2247 F: FnOnce(&mut SceneTree) -> R,
2248 {
2249 let Self { inner } = self;
2250 match inner.try_borrow_mut() {
2251 Ok(mut guard) => operation(&mut guard),
2252 Err(_) => fallback,
2253 }
2254 }
2255
2256 pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2268 where
2269 F: FnMut() -> String + 'static,
2270 {
2271 let handle: Self = self.clone();
2272 Effect::new(move || {
2273 let value: String = producer();
2274 handle.with_write(
2275 |tree: &mut SceneTree| {
2276 tree.set_text(node_id, value);
2277 },
2278 (),
2279 );
2280 })
2281 }
2282
2283 pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2295 where
2296 F: FnMut() -> Style + 'static,
2297 {
2298 let handle: Self = self.clone();
2299 Effect::new(move || {
2300 let style: Style = producer();
2301 handle.with_write(
2302 |tree: &mut SceneTree| {
2303 tree.set_style(node_id, style);
2304 },
2305 (),
2306 );
2307 })
2308 }
2309}
2310
2311impl Context {
2313 #[must_use]
2324 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
2325 Self {
2326 scene,
2327 breakpoint: Signal::new(Breakpoint::Expanded),
2328 viewport_size: Signal::new(Size::new(1200.0, 800.0)),
2329 theme_mode: Signal::new(ThemeMode::Light),
2330 platform,
2331 safe_area: Signal::new(SafeAreaInsets::default()),
2332 gesture: Signal::new(None),
2333 swipe_drag_offset: Signal::new(0.0),
2334 system_back: Signal::new(0),
2335 dynamic_hub: DynamicUpdateHub::new(),
2336 fps_limit: Signal::new(None),
2337 live_fps: Signal::new(60.0),
2338 present_fps: Signal::new(0.0),
2339 is_idle: Signal::new(true),
2340 display_refresh_rate: Signal::new(60.0),
2341 active_touches: Signal::new(Vec::new()),
2342 exit_requested: Signal::new(false),
2343 app_state: Signal::new(AppState::Active),
2344 network_status: Signal::new(NetworkStatus::Online),
2345 keyboard_visible: Signal::new(false),
2346 keyboard_height: Signal::new(0.0),
2347 orientation: Signal::new(ScreenOrientation::Landscape),
2348 low_power_mode: Signal::new(false),
2349 locale: Signal::new(DEFAULT_SYSTEM_LOCALE.to_string()),
2350 window_focused: Signal::new(true),
2351 immersive_fullscreen: Signal::new(false),
2352 fullscreen_depth: Rc::new(Cell::new(0)),
2353 clock_ms: Rc::new(Cell::new(0)),
2354 }
2355 }
2356
2357 #[must_use]
2367 pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
2368 self.get_safe_area()
2369 }
2370
2371 #[must_use]
2381 pub fn safe_area(&self) -> SafeAreaInsets {
2382 self.get_safe_area().get()
2383 }
2384
2385 #[must_use]
2395 pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
2396 self.get_immersive_fullscreen()
2397 }
2398
2399 #[must_use]
2409 pub fn is_immersive_fullscreen(&self) -> bool {
2410 self.get_immersive_fullscreen().get()
2411 }
2412
2413 pub fn set_immersive_fullscreen(&self, enabled: bool) {
2420 let Self {
2421 fullscreen_depth, ..
2422 } = self;
2423 if enabled {
2424 if fullscreen_depth.get() == 0 {
2425 fullscreen_depth.set(1);
2426 }
2427 let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
2428 } else {
2429 fullscreen_depth.set(0);
2430 let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
2431 }
2432 }
2433
2434 pub fn enter_immersive_fullscreen(&self) {
2440 let Self {
2441 fullscreen_depth, ..
2442 } = self;
2443 let next: u32 = fullscreen_depth.get().saturating_add(1);
2444 fullscreen_depth.set(next);
2445 let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
2446 }
2447
2448 pub fn exit_immersive_fullscreen(&self) {
2454 let Self {
2455 fullscreen_depth, ..
2456 } = self;
2457 let next: u32 = fullscreen_depth.get().saturating_sub(1);
2458 fullscreen_depth.set(next);
2459 if next == 0 {
2460 let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
2461 }
2462 }
2463
2464 #[must_use]
2474 pub fn app_state_signal(&self) -> Signal<AppState> {
2475 self.get_app_state()
2476 }
2477
2478 pub fn emit_page_appear(&self) {
2484 let ev: SystemEvent = SystemEvent::Appear;
2485 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2486 .get_scene()
2487 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2488 dispatch_lifecycle_system_event(&observers, &ev);
2489 dispatch_system_event_listeners(&ev);
2490 }
2491
2492 pub fn emit_page_disappear(&self) {
2498 let ev: SystemEvent = SystemEvent::Disappear;
2499 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2500 .get_scene()
2501 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2502 dispatch_lifecycle_system_event(&observers, &ev);
2503 dispatch_system_event_listeners(&ev);
2504 }
2505
2506 pub fn emit_subtree_appear(&self, root: NodeId) {
2513 self.get_scene().emit_subtree_appear(root);
2514 }
2515
2516 pub fn emit_subtree_disappear(&self, root: NodeId) {
2523 self.get_scene().emit_subtree_disappear(root);
2524 }
2525
2526 #[must_use]
2536 pub fn elapsed_ms(&self) -> u64 {
2537 let Self { clock_ms, .. } = self;
2538 clock_ms.get()
2539 }
2540
2541 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
2548 let Self { clock_ms, .. } = self;
2549 clock_ms.set(clock_ms.get().saturating_add(delta_ms));
2550 }
2551
2552 pub fn request_exit(&self) {
2558 let _: bool = self.get_exit_requested().set_if_changed(true);
2559 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
2560 }
2561
2562 pub fn copy_to_clipboard(&self, text: &str) -> bool {
2573 write_system_clipboard(text)
2574 }
2575
2576 pub fn view(&mut self, style: Style) -> NodeId {
2587 self.get_scene().with_write(
2588 |tree: &mut SceneTree| tree.create_view(style),
2589 NodeId::default(),
2590 )
2591 }
2592
2593 pub fn text(&mut self, content: String, style: Style) -> NodeId {
2605 self.get_scene().with_write(
2606 |tree: &mut SceneTree| tree.create_text(content, style),
2607 NodeId::default(),
2608 )
2609 }
2610
2611 pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
2623 where
2624 F: FnMut() -> String + 'static,
2625 {
2626 let node_id: NodeId = self.text(String::new(), style);
2627 let handle: SceneHandle = self.get_scene().clone();
2628 let (scope, _): (Scope, Effect) =
2629 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
2630 self.get_scene().with_write(
2631 |tree: &mut SceneTree| {
2632 tree.attach_scope(node_id, scope);
2633 },
2634 (),
2635 );
2636 node_id
2637 }
2638
2639 pub fn scroll_view(&mut self, style: Style) -> NodeId {
2650 self.get_scene().with_write(
2651 |tree: &mut SceneTree| tree.create_scroll_view(style),
2652 NodeId::default(),
2653 )
2654 }
2655
2656 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
2668 self.get_scene().with_write(
2669 |tree: &mut SceneTree| tree.create_input(state, style),
2670 NodeId::default(),
2671 )
2672 }
2673
2674 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
2686 self.get_scene().with_write(
2687 |tree: &mut SceneTree| tree.create_image(buffer, style),
2688 NodeId::default(),
2689 )
2690 }
2691
2692 pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
2704 where
2705 F: FnMut(Rect, &mut DisplayList) + 'static,
2706 {
2707 let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
2708 self.get_scene().with_write(
2709 |tree: &mut SceneTree| tree.create_canvas(style, cb),
2710 NodeId::default(),
2711 )
2712 }
2713
2714 pub fn portal(&mut self, style: Style) -> NodeId {
2725 self.get_scene().with_write(
2726 |tree: &mut SceneTree| tree.create_portal(style),
2727 NodeId::default(),
2728 )
2729 }
2730
2731 pub fn fragment(&mut self) -> NodeId {
2741 self.get_scene().with_write(
2742 |tree: &mut SceneTree| tree.create_fragment(),
2743 NodeId::default(),
2744 )
2745 }
2746
2747 pub fn append(&mut self, parent: NodeId, child: NodeId) {
2755 self.get_scene().with_write(
2756 |tree: &mut SceneTree| {
2757 tree.append_child(parent, child);
2758 },
2759 (),
2760 );
2761 }
2762
2763 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
2771 if children.is_empty() {
2772 return;
2773 }
2774 self.get_scene().with_write(
2775 |tree: &mut SceneTree| {
2776 tree.append_children(parent, children);
2777 },
2778 (),
2779 );
2780 }
2781
2782 pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
2790 where
2791 F: FnMut() -> Style + 'static,
2792 {
2793 let handle: SceneHandle = self.get_scene().clone();
2794 let (scope, _): (Scope, Effect) =
2795 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
2796 self.get_scene().with_write(
2797 |tree: &mut SceneTree| {
2798 tree.attach_scope(node_id, scope);
2799 },
2800 (),
2801 );
2802 }
2803
2804 pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
2812 where
2813 F: FnMut(&UiEvent) + 'static,
2814 {
2815 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2816 self.get_scene().with_write(
2817 |tree: &mut SceneTree| {
2818 if let Some(node) = tree.get_node_mut(node_id) {
2819 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
2820 }
2821 },
2822 (),
2823 );
2824 }
2825
2826 pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
2834 where
2835 F: FnMut(&UiEvent) + 'static,
2836 {
2837 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2838 self.get_scene().with_write(
2839 |tree: &mut SceneTree| {
2840 if let Some(node) = tree.get_node_mut(node_id) {
2841 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
2842 }
2843 },
2844 (),
2845 );
2846 }
2847
2848 pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
2856 where
2857 F: FnMut(&UiEvent) + 'static,
2858 {
2859 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2860 self.get_scene().with_write(
2861 |tree: &mut SceneTree| {
2862 if let Some(node) = tree.get_node_mut(node_id) {
2863 node.get_mut_handlers().set_on_focus(Some(handler));
2864 node.get_mut_interaction().set_focusable(true);
2865 }
2866 },
2867 (),
2868 );
2869 }
2870
2871 pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
2879 where
2880 F: FnMut(&UiEvent) + 'static,
2881 {
2882 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2883 self.get_scene().with_write(
2884 |tree: &mut SceneTree| {
2885 if let Some(node) = tree.get_node_mut(node_id) {
2886 node.get_mut_handlers().set_on_blur(Some(handler));
2887 }
2888 },
2889 (),
2890 );
2891 }
2892
2893 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
2901 self.get_scene().with_write(
2902 |tree: &mut SceneTree| {
2903 if let Some(node) = tree.get_node_mut(node_id) {
2904 node.get_mut_interaction().set_focusable(focusable);
2905 }
2906 },
2907 (),
2908 );
2909 }
2910
2911 pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
2919 where
2920 F: FnMut(&UiEvent) + 'static,
2921 {
2922 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2923 self.get_scene().with_write(
2924 |tree: &mut SceneTree| {
2925 if let Some(node) = tree.get_node_mut(node_id) {
2926 node.get_mut_handlers().set_on_click(Some(handler));
2927 node.get_mut_interaction().set_focusable(true);
2928 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
2929 if paint.get_cursor() == CursorIcon::Default {
2930 paint.set_cursor(CursorIcon::Pointer);
2931 }
2932 }
2933 },
2934 (),
2935 );
2936 }
2937
2938 pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
2946 where
2947 F: FnMut(&UiEvent) + 'static,
2948 {
2949 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2950 self.get_scene().with_write(
2951 |tree: &mut SceneTree| {
2952 if let Some(node) = tree.get_node_mut(node_id) {
2953 node.get_mut_handlers().set_on_change(Some(handler));
2954 }
2955 },
2956 (),
2957 );
2958 }
2959
2960 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
2968 self.get_scene().with_write(
2969 |tree: &mut SceneTree| {
2970 if let Some(node) = tree.get_node_mut(node_id) {
2971 node.set_a11y(Some(props));
2972 }
2973 },
2974 (),
2975 );
2976 }
2977
2978 pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
2986 where
2987 F: FnMut(&UiEvent) + 'static,
2988 {
2989 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2990 self.get_scene().with_write(
2991 |tree: &mut SceneTree| {
2992 if let Some(node) = tree.get_node_mut(node_id) {
2993 node.get_mut_handlers().set_on_scroll(Some(handler));
2994 }
2995 },
2996 (),
2997 );
2998 }
2999
3000 pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
3008 where
3009 F: FnMut(&UiEvent) + 'static,
3010 {
3011 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3012 self.get_scene().with_write(
3013 |tree: &mut SceneTree| {
3014 if let Some(node) = tree.get_node_mut(node_id) {
3015 node.get_mut_handlers().set_on_pointer_down(Some(handler));
3016 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
3017 if paint.get_cursor() == CursorIcon::Default {
3018 paint.set_cursor(CursorIcon::Pointer);
3019 }
3020 }
3021 },
3022 (),
3023 );
3024 }
3025
3026 pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
3034 where
3035 F: FnMut(&UiEvent) + 'static,
3036 {
3037 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3038 self.get_scene().with_write(
3039 |tree: &mut SceneTree| {
3040 if let Some(node) = tree.get_node_mut(node_id) {
3041 node.get_mut_handlers().set_on_pointer_move(Some(handler));
3042 }
3043 },
3044 (),
3045 );
3046 }
3047
3048 pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
3056 where
3057 F: FnMut(&UiEvent) + 'static,
3058 {
3059 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3060 self.get_scene().with_write(
3061 |tree: &mut SceneTree| {
3062 if let Some(node) = tree.get_node_mut(node_id) {
3063 node.get_mut_handlers().set_on_pointer_up(Some(handler));
3064 }
3065 },
3066 (),
3067 );
3068 }
3069
3070 pub fn on_pointer_cancel<F>(&mut self, node_id: NodeId, callback: F)
3078 where
3079 F: FnMut(&UiEvent) + 'static,
3080 {
3081 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3082 self.get_scene().with_write(
3083 |tree: &mut SceneTree| {
3084 if let Some(node) = tree.get_node_mut(node_id) {
3085 node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
3086 }
3087 },
3088 (),
3089 );
3090 }
3091
3092 pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
3100 where
3101 F: FnMut(&UiEvent) + 'static,
3102 {
3103 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3104 let leave_handler: UiEventHandler = handler.clone();
3105 self.get_scene().with_write(
3106 |tree: &mut SceneTree| {
3107 if let Some(node) = tree.get_node_mut(node_id) {
3108 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
3109 node.get_mut_handlers()
3110 .set_on_pointer_leave(Some(leave_handler));
3111 }
3112 },
3113 (),
3114 );
3115 }
3116
3117 pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
3125 where
3126 F: FnMut(&UiEvent) + 'static,
3127 {
3128 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3129 self.get_scene().with_write(
3130 |tree: &mut SceneTree| {
3131 if let Some(node) = tree.get_node_mut(node_id) {
3132 node.get_mut_handlers().set_on_key_down(Some(handler));
3133 node.get_mut_interaction().set_focusable(true);
3134 }
3135 },
3136 (),
3137 );
3138 }
3139
3140 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
3149 self.get_scene()
3150 .set_virtual_scroll(node_id, scroll_y, content_height);
3151 }
3152
3153 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
3161 self.get_scene().with_write(
3162 |tree: &mut SceneTree| {
3163 tree.set_scroll_offset(node_id, offset);
3164 },
3165 (),
3166 );
3167 }
3168
3169 pub fn start_transition(&mut self, transition: NodeTransition) {
3176 self.get_scene().start_transition(transition);
3177 }
3178
3179 pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
3187 where
3188 F: FnMut() -> Vec<NodeId> + 'static,
3189 {
3190 let ctx_clone: Self = self.clone();
3191 let handle: SceneHandle = self.get_scene().clone();
3192 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3193 Effect::new(move || {
3194 let (child_scope, children): (Scope, Vec<NodeId>) =
3195 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
3196 let first_opt: Option<NodeId> = children.first().copied();
3197 handle.replace_children_safe(host, children);
3198 if let Some(first) = first_opt {
3199 handle.with_write(
3200 |tree: &mut SceneTree| {
3201 tree.attach_scope(first, child_scope);
3202 },
3203 (),
3204 );
3205 }
3206 })
3207 });
3208 self.get_scene().with_write(
3209 |tree: &mut SceneTree| {
3210 tree.attach_scope(host, scope);
3211 },
3212 (),
3213 );
3214 }
3215}
3216
3217impl Drop for ContextGuard {
3219 fn drop(&mut self) {
3225 let Self { previous } = self;
3226 let restored: Option<Context> = previous.take();
3227 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
3228 *slot.borrow_mut() = restored;
3229 });
3230 }
3231}
3232
3233impl NodeRefTarget for NodeId {
3235 fn bind_node_ref(&mut self, id: NodeId) {
3242 *self = id;
3243 }
3244}
3245
3246impl NodeRefTarget for Option<NodeId> {
3248 fn bind_node_ref(&mut self, id: NodeId) {
3255 *self = Some(id);
3256 }
3257}
3258
3259impl NodeRefTarget for Cell<NodeId> {
3261 fn bind_node_ref(&mut self, id: NodeId) {
3268 self.set(id);
3269 }
3270}
3271
3272impl NodeRefTarget for Rc<Cell<NodeId>> {
3274 fn bind_node_ref(&mut self, id: NodeId) {
3281 self.set(id);
3282 }
3283}
3284
3285impl NodeRefTarget for Cell<Option<NodeId>> {
3287 fn bind_node_ref(&mut self, id: NodeId) {
3294 self.set(Some(id));
3295 }
3296}
3297
3298impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
3300 fn bind_node_ref(&mut self, id: NodeId) {
3307 self.set(Some(id));
3308 }
3309}
3310
3311impl TextNodeContent for String {
3313 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3325 ctx.text(self, style)
3326 }
3327}
3328
3329impl TextNodeContent for &str {
3331 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3343 ctx.text(self.to_string(), style)
3344 }
3345}
3346
3347impl TextNodeContent for &String {
3349 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3361 ctx.text(self.clone(), style)
3362 }
3363}
3364
3365impl TextNodeContent for Cow<'_, str> {
3367 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3379 ctx.text(self.into_owned(), style)
3380 }
3381}
3382
3383impl<F, S> TextNodeContent for F
3385where
3386 F: FnMut() -> S + 'static,
3387 S: Into<String>,
3388{
3389 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
3401 ctx.reactive_text(style, move || self().into())
3402 }
3403}