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 }
126 let next_rev: u64 = self.get_revision().wrapping_add(1);
127 self.set_revision(next_rev);
128 id
129 }
130
131 pub fn create_view(&mut self, style: Style) -> NodeId {
142 self.create_node(NodeKind::View, style)
143 }
144
145 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
157 self.create_node(NodeKind::Text(content), style)
158 }
159
160 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
172 self.create_node(NodeKind::Input(state), style)
173 }
174
175 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
187 self.create_node(NodeKind::Image(buffer), style)
188 }
189
190 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
201 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
202 }
203
204 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
216 let id: NodeId = self.create_node(NodeKind::Canvas, style);
217 if let Some(node) = self.get_node_mut(id) {
218 node.set_canvas_painter(Some(painter));
219 }
220 id
221 }
222
223 pub fn create_portal(&mut self, style: Style) -> NodeId {
234 self.create_node(NodeKind::Portal, style)
235 }
236
237 pub fn create_fragment(&mut self) -> NodeId {
247 self.create_node(NodeKind::Fragment, Style::default())
248 }
249
250 #[must_use]
261 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
262 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
263 if node.get_alive() && node.get_generation() == id.get_generation() {
264 Some(node)
265 } else {
266 None
267 }
268 }
269
270 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
281 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
282 if node.get_alive() && node.get_generation() == id.get_generation() {
283 Some(node)
284 } else {
285 None
286 }
287 }
288
289 #[must_use]
299 #[inline(always)]
300 pub fn live_node_count(&self) -> usize {
301 self.get_live_count()
302 }
303
304 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
312 if parent == child {
313 return;
314 }
315 let prev_parent: Option<NodeId> = self.get_node(child).and_then(SceneNode::parent_id);
316 if let Some(old_parent) = prev_parent {
317 if old_parent != parent {
318 self.record_subtree_logical_damage(child);
319 }
320 if let Some(old_node) = self.get_node_mut(old_parent) {
321 old_node
322 .get_mut_children()
323 .retain(|item: &NodeId| *item != child);
324 if old_parent != parent {
325 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
326 }
327 }
328 }
329 if let Some(child_node) = self.get_node_mut(child) {
330 child_node.set_parent(Some(parent));
331 } else {
332 return;
333 }
334 if let Some(parent_node) = self.get_node_mut(parent) {
335 parent_node.get_mut_children().push(child);
336 }
337 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
338 }
339
340 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
348 if children.is_empty() || self.get_node(parent).is_none() {
349 return;
350 }
351 let all_fresh_orphans: bool = children.iter().copied().all(|child: NodeId| {
352 child != parent
353 && self
354 .get_node(child)
355 .is_some_and(|node: &SceneNode| node.parent_id().is_none())
356 });
357 if all_fresh_orphans {
358 for child in children.iter().copied() {
359 if let Some(child_node) = self.get_node_mut(child) {
360 child_node.set_parent(Some(parent));
361 }
362 }
363 if let Some(parent_node) = self.get_node_mut(parent) {
364 parent_node.get_mut_children().extend_from_slice(children);
365 }
366 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
367 return;
368 }
369 let mut attached: Vec<NodeId> = Vec::with_capacity(children.len());
370 for child in children.iter().copied() {
371 if child == parent {
372 continue;
373 }
374 let prev_parent: Option<NodeId> = self
375 .get_node(child)
376 .and_then(|node: &SceneNode| node.parent_id());
377 if let Some(old_parent) = prev_parent {
378 if old_parent != parent {
379 self.record_subtree_logical_damage(child);
380 }
381 if let Some(old_node) = self.get_node_mut(old_parent) {
382 old_node
383 .get_mut_children()
384 .retain(|id: &NodeId| *id != child);
385 }
386 if old_parent != parent {
387 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
388 }
389 }
390 if let Some(child_node) = self.get_node_mut(child) {
391 child_node.set_parent(Some(parent));
392 attached.push(child);
393 }
394 }
395 if attached.is_empty() {
396 return;
397 }
398 if let Some(parent_node) = self.get_node_mut(parent) {
399 parent_node.get_mut_children().extend(attached);
400 }
401 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
402 }
403
404 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
412 let old_children: Vec<NodeId> = match self.get_node_mut(parent) {
413 Some(node) => take(node.get_mut_children()),
414 None => return,
415 };
416 if new_children.is_empty() {
417 for old_child in old_children.into_iter() {
418 self.dispose_subtree(old_child);
419 }
420 } else if old_children.len() > 16 && new_children.len() > 16 {
421 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
422 for old_child in old_children.into_iter() {
423 if !keep_set.contains(&old_child) {
424 self.dispose_subtree(old_child);
425 }
426 }
427 } else {
428 for old_child in old_children.into_iter() {
429 if !new_children.contains(&old_child) {
430 self.dispose_subtree(old_child);
431 }
432 }
433 }
434 for child in new_children.iter().copied() {
435 if let Some(child_node) = self.get_node_mut(child) {
436 child_node.set_parent(Some(parent));
437 }
438 }
439 if let Some(parent_node) = self.get_node_mut(parent) {
440 parent_node.set_children(new_children);
441 }
442 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
443 }
444
445 #[inline]
457 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
458 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
459 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
460 if layout_changed || text_metrics_changed {
461 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
462 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
463 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
464 Some(next_fixed)
465 } else {
466 None
467 };
468 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
469 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
470 let mask: u16 = layout_bits | visual_bits;
471 return (mask, portal_update);
472 }
473 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
474 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
475 if paint_changed || text_visual_changed {
476 (DIRTY_PAINT, None)
477 } else {
478 (DIRTY_NONE, None)
479 }
480 }
481
482 #[inline]
493 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
494 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
495 let transform_changed: bool = prev.get_transform() != next.get_transform();
496 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
497 let focus_removed: bool =
498 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
499 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
500 let a: bool = shadow_changed || transform_changed;
501 let b: bool = border_shrank || focus_removed;
502 let ab: bool = a || b;
503 ab || opacity_toggled_zero
504 }
505
506 pub fn set_style(&mut self, id: NodeId, style: Style) {
514 let pre_snapshot: Option<(u16, Option<bool>, bool, bool)> =
515 self.get_node(id).map(|node: &SceneNode| {
516 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
517 let prev: &Style = node.style_ref();
518 let (mask, update): (u16, Option<bool>) =
519 Self::diff_style_change(prev, &style, is_portal_kind);
520 let pre_paint: bool = mask != DIRTY_NONE
521 && Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
522 let subtree_hidden: bool = pre_paint
523 && (prev.paint_ref().get_opacity() > 0.0)
524 != (style.paint_ref().get_opacity() > 0.0)
525 && !node.get_children().is_empty();
526 (mask, update, pre_paint, subtree_hidden)
527 });
528 let Some((dirty_mask, portal_update, pre_paint, subtree_hidden)) = pre_snapshot else {
529 return;
530 };
531 if dirty_mask == DIRTY_NONE {
532 return;
533 }
534 if subtree_hidden {
535 self.record_subtree_logical_damage(id);
536 } else if pre_paint {
537 self.record_node_logical_damage(id);
538 }
539 if let Some(node) = self.get_node_mut(id) {
540 node.set_style(style);
541 }
542 if let Some(is_portal) = portal_update {
543 self.sync_portal_registration(id, is_portal);
544 }
545 self.mark_dirty(id, dirty_mask);
546 }
547
548 pub fn mutate_style<F>(&mut self, id: NodeId, mutator: F) -> bool
560 where
561 F: FnOnce(&mut Style),
562 {
563 let prev_opt: Option<(Style, bool, bool)> = self.get_node(id).map(|node: &SceneNode| {
564 (
565 *node.style_ref(),
566 matches!(node.get_kind(), NodeKind::Portal),
567 !node.get_children().is_empty(),
568 )
569 });
570 let Some((prev, is_portal_kind, has_children)) = prev_opt else {
571 return false;
572 };
573 let mut next: Style = prev;
574 mutator(&mut next);
575 let (dirty_mask, portal_update): (u16, Option<bool>) =
576 Self::diff_style_change(&prev, &next, is_portal_kind);
577 if dirty_mask == DIRTY_NONE {
578 return false;
579 }
580 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
581 if pre_paint {
582 let opacity_toggled_zero: bool =
583 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
584 if opacity_toggled_zero && has_children {
585 self.record_subtree_logical_damage(id);
586 } else {
587 self.record_node_logical_damage(id);
588 }
589 }
590 if let Some(node) = self.get_node_mut(id) {
591 node.set_style(next);
592 }
593 if let Some(is_portal) = portal_update {
594 self.sync_portal_registration(id, is_portal);
595 }
596 self.mark_dirty(id, dirty_mask);
597 true
598 }
599
600 pub fn set_text(&mut self, id: NodeId, text: String) {
608 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
609 Some(node) => {
610 let layout: &LayoutStyle = node.style_ref().layout_ref();
611 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
612 && matches!(layout.get_height(), Length::Px(_));
613 match node.get_mut_kind() {
614 NodeKind::Text(current) => {
615 if *current == text {
616 (false, has_fixed)
617 } else {
618 *current = text;
619 (true, has_fixed)
620 }
621 }
622 _ => (false, false),
623 }
624 }
625 None => (false, false),
626 };
627 if changed {
628 let mask: u16 = if fixed_size {
629 DIRTY_PAINT
630 } else {
631 DIRTY_TEXT_CHANGE_MASK
632 };
633 self.mark_dirty(id, mask);
634 }
635 }
636
637 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
645 let changed: bool = match self.get_node_mut(id) {
646 Some(node) => {
647 let layout_box: LayoutBox = node.get_layout_box();
648 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
649 && layout_box.get_content_size().get_height() <= 0.0
650 && layout_box.get_content_bounds().get_width() <= 0.0
651 && layout_box.get_content_bounds().get_height() <= 0.0;
652 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
653 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
654 } else {
655 let max_x: f32 = (layout_box.get_content_size().get_width()
656 - layout_box.get_content_bounds().get_width())
657 .max(0.0);
658 let max_y: f32 = (layout_box.get_content_size().get_height()
659 - layout_box.get_content_bounds().get_height())
660 .max(0.0);
661 Point::new(
662 offset.get_x().clamp(0.0, max_x),
663 offset.get_y().clamp(0.0, max_y),
664 )
665 };
666 if layout_box.get_scroll_offset() == clamped {
667 false
668 } else {
669 node.get_mut_layout_box().set_scroll_offset(clamped);
670 true
671 }
672 }
673 None => false,
674 };
675 if changed {
676 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
677 }
678 }
679
680 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
689 let changed: bool = match self.get_node_mut(id) {
690 Some(node) => {
691 let next: Option<(f32, f32)> = Some((scroll_y.max(0.0), content_height.max(1.0)));
692 if node.virtual_scroll_metrics() == next {
693 false
694 } else {
695 node.set_virtual_scroll(next);
696 true
697 }
698 }
699 None => false,
700 };
701 if changed {
702 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
703 }
704 }
705
706 #[must_use]
717 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
718 let node: &SceneNode = self.get_node(id)?;
719 let raw: Rect = node.get_layout_box().get_bounds();
720 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
721 self.node_scroll_and_transform(node);
722 Some(Rect::new(
723 raw.get_x() - off.get_x() + tx,
724 raw.get_y() - off.get_y() + ty,
725 raw.get_width() * sx,
726 raw.get_height() * sy,
727 ))
728 }
729
730 #[inline]
741 fn node_scroll_and_transform(&self, node: &SceneNode) -> (Point, f32, f32, f32, f32) {
742 let style: &Style = node.style_ref();
743 let tr: Transform2D = style.get_paint().get_transform();
744 let mut tx: f32 = tr.get_translate_x();
745 let mut ty: f32 = tr.get_translate_y();
746 let sx_scale: f32 = tr.get_scale_x();
747 let sy_scale: f32 = tr.get_scale_y();
748 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
749 || style.get_layout().get_position() == Position::Fixed;
750 let mut scroll_x: f32 = 0.0;
751 let mut scroll_y: f32 = 0.0;
752 let mut cursor: Option<NodeId> = node.parent_id();
753 while let Some(pid) = cursor {
754 if let Some(pnode) = self.get_node(pid) {
755 let pstyle: &Style = pnode.style_ref();
756 let ptr: Transform2D = pstyle.get_paint().get_transform();
757 tx += ptr.get_translate_x();
758 ty += ptr.get_translate_y();
759 if !start_top_layer {
760 let off: Point = pnode.get_layout_box().get_scroll_offset();
761 scroll_x += off.get_x();
762 scroll_y += off.get_y();
763 }
764 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
765 || pstyle.get_layout().get_position() == Position::Fixed;
766 if parent_top_layer {
767 break;
768 }
769 cursor = pnode.parent_id();
770 } else {
771 break;
772 }
773 }
774 (Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale)
775 }
776
777 #[must_use]
790 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
791 let node: &SceneNode = self.get_node(id)?;
792 let raw_bounds: Rect = node.get_layout_box().get_bounds();
793 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
794 return Some(Rect::default());
795 }
796 let style: &Style = node.style_ref();
797 let paint: &PaintStyle = style.paint_ref();
798 let tr: Transform2D = paint.get_transform();
799 if tr.get_rotation_rad().abs() > 0.0001
800 || tr.get_scale_x() <= 0.0
801 || tr.get_scale_y() <= 0.0
802 {
803 return None;
804 }
805 let mut tx: f32 = tr.get_translate_x();
806 let mut ty: f32 = tr.get_translate_y();
807 let sx: f32 = tr.get_scale_x();
808 let sy: f32 = tr.get_scale_y();
809 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
810 || style.layout_ref().get_position() == Position::Fixed;
811 let mut scroll_x: f32 = 0.0;
812 let mut scroll_y: f32 = 0.0;
813 let mut cursor: Option<NodeId> = node.parent_id();
814 while let Some(pid) = cursor {
815 let Some(pnode) = self.get_node(pid) else {
816 break;
817 };
818 let pstyle: &Style = pnode.style_ref();
819 let ptr: Transform2D = pstyle.paint_ref().get_transform();
820 if ptr.get_rotation_rad().abs() > 0.0001
821 || (ptr.get_scale_x() - 1.0).abs() > 0.001
822 || (ptr.get_scale_y() - 1.0).abs() > 0.001
823 {
824 return None;
825 }
826 tx += ptr.get_translate_x();
827 ty += ptr.get_translate_y();
828 if !start_top_layer {
829 let off: Point = pnode.get_layout_box().get_scroll_offset();
830 scroll_x += off.get_x();
831 scroll_y += off.get_y();
832 }
833 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
834 || pstyle.layout_ref().get_position() == Position::Fixed;
835 if parent_top_layer {
836 break;
837 }
838 cursor = pnode.parent_id();
839 }
840 let border_w: f32 = paint.get_border().get_width();
841 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
842 12.0
843 } else {
844 0.0
845 };
846 let mut margin: f32 = 10.0_f32.max(border_w + 6.0).max(focus_pad);
847 if let Some(shadow) = paint.box_shadow() {
848 let blur_pad: f32 = (shadow.get_blur_radius().max(0.5) * 1.5).min(96.0) + 4.0;
849 let spread: f32 = shadow.get_spread_radius().max(0.0);
850 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
851 margin = margin.max(blur_pad + spread + off_max + 4.0);
852 }
853 let base_x: f32 = raw_bounds.get_x() - scroll_x;
854 let base_y: f32 = raw_bounds.get_y() - scroll_y;
855 let base_rect: Rect = Rect::new(
856 base_x - margin,
857 base_y - margin,
858 raw_bounds.get_width() + margin * 2.0,
859 raw_bounds.get_height() + margin * 2.0,
860 );
861 let shifted_x: bool = tx != 0.0 || sx != 1.0;
862 let shifted_y: bool = ty != 0.0 || sy != 1.0;
863 if shifted_x || shifted_y {
864 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
865 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
866 let shifted_rect: Rect = Rect::new(
867 base_x + tx - margin - scale_pad_x,
868 base_y + ty - margin - scale_pad_y,
869 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
870 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
871 );
872 Some(base_rect.union(shifted_rect))
873 } else {
874 Some(base_rect)
875 }
876 }
877
878 #[must_use]
889 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
890 let x0: f32 = (logical.get_x() * scale).floor();
891 let y0: f32 = (logical.get_y() * scale).floor();
892 let x1: f32 = (logical.right() * scale).ceil();
893 let y1: f32 = (logical.bottom() * scale).ceil();
894 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
895 }
896
897 fn record_node_logical_damage(&mut self, id: NodeId) {
904 if self.get_full_damage_pending() {
905 return;
906 }
907 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
908 match rect_opt {
909 Some(rect) => {
910 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
911 return;
912 }
913 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
914 self.set_full_damage_pending(true);
915 self.set_full_damage_overflow(true);
916 self.get_mut_extra_logical_damage().clear();
917 } else {
918 self.get_mut_extra_logical_damage().push(rect);
919 }
920 }
921 None => {
922 self.set_full_damage_pending(true);
923 }
924 }
925 }
926
927 fn record_subtree_logical_damage(&mut self, root: NodeId) {
934 if self.get_full_damage_pending() {
935 return;
936 }
937 let mut stack: Vec<NodeId> = vec![root];
938 let mut visited: usize = 0;
939 while let Some(current) = stack.pop() {
940 let Some(node) = self.get_node(current) else {
941 continue;
942 };
943 visited += 1;
944 if visited > DIRTY_PAINT_FULL_THRESHOLD {
945 self.set_full_damage_pending(true);
946 self.set_full_damage_overflow(true);
947 self.get_mut_extra_logical_damage().clear();
948 return;
949 }
950 let children: Vec<NodeId> = node.get_children().clone();
951 let raw_bounds: Rect = node.get_layout_box().get_bounds();
952 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
953 self.record_node_logical_damage(current);
954 if self.get_full_damage_pending() {
955 return;
956 }
957 }
958 for child in children.into_iter() {
959 stack.push(child);
960 }
961 }
962 }
963
964 pub fn start_transition(&mut self, mut transition: NodeTransition) {
971 let target: NodeId = transition.get_node();
972 let had_active: bool = self
973 .get_transitions()
974 .iter()
975 .any(|tr: &NodeTransition| tr.get_node() == target);
976 self.get_mut_transitions()
977 .retain(|tr: &NodeTransition| tr.get_node() != target);
978 if had_active && let Some(node) = self.get_node(target) {
979 let paint: PaintStyle = node.get_style().get_paint();
980 let tr: Transform2D = paint.get_transform();
981 let cur_op: f32 = paint.get_opacity();
982 let cur_tx: f32 = tr.get_translate_x();
983 let cur_ty: f32 = tr.get_translate_y();
984 let cur_sc: f32 = tr.get_scale_x();
985 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
986 .hypot(transition.get_to_ty() - transition.get_from_ty())
987 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
988 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
989 .hypot(transition.get_to_ty() - cur_ty)
990 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
991 if full_dist > 0.01 {
992 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
993 transition.set_duration((transition.get_duration() * ratio).max(0.05));
994 }
995 transition.set_from_opacity(cur_op);
996 transition.set_from_tx(cur_tx);
997 transition.set_from_ty(cur_ty);
998 transition.set_from_scale(cur_sc);
999 }
1000 let (opacity, transform): (f32, Transform2D) = transition.sample();
1001 let mut unhidden: bool = false;
1002 if let Some(node) = self.get_node_mut(target) {
1003 let style: &mut Style = node.get_mut_style();
1004 if !transition.get_hide_on_complete()
1005 && style.layout_ref().get_display() == Display::None
1006 {
1007 style.get_mut_layout().set_display(Display::Flex);
1008 unhidden = true;
1009 }
1010 style.get_mut_paint().set_opacity(opacity);
1011 style.get_mut_paint().set_transform(transform);
1012 }
1013 if unhidden {
1014 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1015 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1016 } else {
1017 self.mark_dirty(target, DIRTY_PAINT);
1018 }
1019 self.get_mut_transitions().push(transition);
1020 }
1021
1022 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
1033 let len: usize = self.get_transitions().len();
1034 if len == 0 {
1035 return false;
1036 }
1037 let step: f32 = dt_secs.clamp(0.001, 0.05);
1038 let mut any_updated: bool = false;
1039 let mut write_idx: usize = 0;
1040 for read_idx in 0..len {
1041 let target: NodeId = self.get_transitions()[read_idx].get_node();
1042 if self.get_node(target).is_none() {
1043 continue;
1044 }
1045 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
1046 let tr: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
1047 let total_span: f32 = tr.get_delay() + tr.get_duration();
1048 let prev_elapsed: f32 = tr.get_elapsed();
1049 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
1050 tr.set_elapsed(next_elapsed);
1051 let is_done: bool = tr.is_complete();
1052 let in_hold: bool =
1053 prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !is_done;
1054 if in_hold {
1055 (is_done, None, false)
1056 } else {
1057 let sampled: (f32, Transform2D) = tr.sample();
1058 let should_hide: bool = is_done && tr.get_hide_on_complete();
1059 (is_done, Some(sampled), should_hide)
1060 }
1061 };
1062 if let Some((opacity, transform)) = sample_opt {
1063 if let Some(node) = self.get_node_mut(target) {
1064 let style: &mut Style = node.get_mut_style();
1065 style.get_mut_paint().set_opacity(opacity);
1066 style.get_mut_paint().set_transform(transform);
1067 if hide {
1068 style.get_mut_layout().set_display(Display::None);
1069 }
1070 }
1071 if hide {
1072 self.clear_subtree_hover(target);
1073 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1074 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1075 } else {
1076 self.mark_dirty(target, DIRTY_PAINT);
1077 }
1078 any_updated = true;
1079 }
1080 if !done {
1081 if write_idx != read_idx {
1082 self.get_mut_transitions().swap(write_idx, read_idx);
1083 }
1084 write_idx += 1;
1085 }
1086 }
1087 self.get_mut_transitions().truncate(write_idx);
1088 any_updated
1089 }
1090
1091 fn clear_subtree_hover(&mut self, root: NodeId) {
1098 let mut stack: Vec<NodeId> = vec![root];
1099 while let Some(id) = stack.pop() {
1100 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(id) {
1101 Some(node) => {
1102 node.get_mut_interaction().set_hovered(false);
1103 node.get_mut_interaction().set_pressed(false);
1104 if node.get_children().is_empty() {
1105 None
1106 } else {
1107 Some(node.get_children().clone())
1108 }
1109 }
1110 None => continue,
1111 };
1112 if let Some(children) = children_opt {
1113 stack.extend(children);
1114 }
1115 }
1116 }
1117
1118 #[must_use]
1128 pub fn has_active_transitions(&self) -> bool {
1129 !self.get_transitions().is_empty()
1130 }
1131
1132 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
1140 if let Some(node) = self.get_node_mut(id) {
1141 node.add_lifecycle(hook);
1142 }
1143 }
1144
1145 #[must_use]
1156 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1157 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1158 let mut stack: Vec<NodeId> = vec![root];
1159 while let Some(current) = stack.pop() {
1160 if let Some(node) = self.get_node(current) {
1161 for hook in node.lifecycle_observers().into_iter() {
1162 out.push((current, hook));
1163 }
1164 for child in node.get_children().iter().rev().copied() {
1165 stack.push(child);
1166 }
1167 }
1168 }
1169 out
1170 }
1171
1172 #[must_use]
1182 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1183 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1184 let mut stack: Vec<NodeId> = vec![self.get_root()];
1185 while let Some(current) = stack.pop() {
1186 if let Some(node) = self.get_node(current) {
1187 if node.style_ref().layout_ref().get_display() == Display::None {
1188 continue;
1189 }
1190 for hook in node.lifecycle_observers().into_iter() {
1191 out.push((current, hook));
1192 }
1193 for child in node.get_children().iter().rev().copied() {
1194 stack.push(child);
1195 }
1196 }
1197 }
1198 out
1199 }
1200
1201 #[must_use]
1212 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
1213 let mut out: Vec<ScopeId> = Vec::new();
1214 let mut stack: Vec<NodeId> = vec![root];
1215 while let Some(current) = stack.pop() {
1216 if let Some(node) = self.get_node(current) {
1217 if let Some(scope) = node.owned_scope() {
1218 out.push(scope.id());
1219 }
1220 for child in node.get_children().iter().rev().copied() {
1221 stack.push(child);
1222 }
1223 }
1224 }
1225 out
1226 }
1227
1228 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
1235 if self.get_transitions().is_empty() {
1236 return;
1237 }
1238 let mut ids: HashSet<NodeId> = HashSet::new();
1239 let mut stack: Vec<NodeId> = vec![root];
1240 while let Some(current) = stack.pop() {
1241 if ids.insert(current)
1242 && let Some(node) = self.get_node(current)
1243 {
1244 for child in node.get_children().iter().copied() {
1245 stack.push(child);
1246 }
1247 }
1248 }
1249 self.get_mut_transitions()
1250 .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
1251 }
1252
1253 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
1261 if let Some(node) = self.get_node_mut(id) {
1262 if let Some(existing) = node.owned_scope() {
1263 existing.enter(|| {
1264 on_cleanup(move || {
1265 scope.dispose();
1266 });
1267 });
1268 } else {
1269 node.set_scope(Some(scope));
1270 }
1271 }
1272 }
1273
1274 pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
1282 let check_portal: bool = (mask & DIRTY_LAYOUT) != 0;
1283 let (prev_bits, mut parent_opt, portal_state): (u16, Option<NodeId>, Option<bool>) =
1284 match self.get_node_mut(id) {
1285 Some(node) => {
1286 let prev: u16 = node.get_dirty().get_bits();
1287 node.get_mut_dirty().insert(mask);
1288 let portal_opt: Option<bool> = if check_portal {
1289 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
1290 || node.style_ref().get_layout().get_position() == Position::Fixed;
1291 Some(is_portal)
1292 } else {
1293 None
1294 };
1295 (prev, node.parent_id(), portal_opt)
1296 }
1297 None => return,
1298 };
1299 if let Some(is_portal) = portal_state
1300 && (is_portal || self.has_portal_nodes())
1301 {
1302 self.sync_portal_registration(id, is_portal);
1303 }
1304 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
1305 self.set_layout_damage_pending(true);
1306 }
1307 let paint_or_scroll: u16 = DIRTY_PAINT | DIRTY_SCROLL;
1308 if !self.get_full_damage_pending()
1309 && (mask & paint_or_scroll) != 0
1310 && (prev_bits & paint_or_scroll) == 0
1311 {
1312 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1313 self.set_full_damage_pending(true);
1314 self.set_full_damage_overflow(true);
1315 self.get_mut_dirty_paint_nodes().clear();
1316 } else {
1317 self.get_mut_dirty_paint_nodes().push(id);
1318 }
1319 }
1320 let mut ancestor_mask: u16 = DIRTY_NONE;
1321 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
1322 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
1323 }
1324 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
1325 ancestor_mask |= DIRTY_SUBTREE_PAINT;
1326 }
1327 while let Some(ancestor_id) = parent_opt {
1328 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1329 let already: bool =
1330 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
1331 ancestor.get_mut_dirty().insert(ancestor_mask);
1332 if already {
1333 break;
1334 }
1335 parent_opt = ancestor.parent_id();
1336 } else {
1337 break;
1338 }
1339 }
1340 let next_rev: u64 = self.get_revision().wrapping_add(1);
1341 self.set_revision(next_rev);
1342 }
1343
1344 #[must_use]
1355 pub fn is_node_visible(&self, id: NodeId) -> bool {
1356 let mut cursor: Option<NodeId> = Some(id);
1357 while let Some(cur) = cursor {
1358 let Some(node) = self.get_node(cur) else {
1359 return false;
1360 };
1361 let style: &Style = node.style_ref();
1362 if style.get_layout().get_display() == Display::None
1363 || style.get_paint().get_opacity() <= 0.0
1364 {
1365 return false;
1366 }
1367 cursor = node.parent_id();
1368 }
1369 true
1370 }
1371
1372 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
1383 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
1384 damage
1385 }
1386
1387 pub(crate) fn collect_surgical_paint_damage(
1399 &mut self,
1400 scale: f32,
1401 allow_partial_layout: bool,
1402 ) -> (DamageRegion, bool) {
1403 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
1404 let layout_pending: bool = self.get_layout_damage_pending();
1405 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
1406 let no_extra: bool = self.get_extra_logical_damage().is_empty();
1407 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
1408 self.set_created_since_damage(0);
1409 return (DamageRegion::default(), false);
1410 }
1411 let mut full: bool =
1412 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
1413 let mut region: DamageRegion = DamageRegion::default();
1414 if !full {
1415 let extra_len: usize = self.get_extra_logical_damage().len();
1416 for i in 0..extra_len {
1417 let logical_rect: Rect = self.get_extra_logical_damage()[i];
1418 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
1419 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1420 }
1421 }
1422 let dirty_len: usize = self.get_dirty_paint_nodes().len();
1423 for i in 0..dirty_len {
1424 let nid: NodeId = self.get_dirty_paint_nodes()[i];
1425 let Some(node) = self.get_node(nid) else {
1426 continue;
1427 };
1428 let bits: u16 = node.get_dirty().get_bits();
1429 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
1430 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
1431 full = true;
1432 break;
1433 }
1434 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
1435 full = true;
1436 break;
1437 }
1438 if (bits & (DIRTY_PAINT | DIRTY_SCROLL)) == 0 {
1439 continue;
1440 }
1441 let raw_bounds: Rect = node.get_layout_box().get_bounds();
1442 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
1443 match self.node_conservative_logical_rect(nid) {
1444 Some(logical_rect) => {
1445 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1446 }
1447 None => {
1448 full = true;
1449 break;
1450 }
1451 }
1452 } else if (bits & DIRTY_PAINT) != 0
1453 && !has_layout_bits
1454 && node.style_ref().layout_ref().get_display() != Display::None
1455 {
1456 full = true;
1457 break;
1458 }
1459 }
1460 }
1461 self.set_layout_damage_pending(false);
1462 self.set_created_since_damage(0);
1463 self.get_mut_extra_logical_damage().clear();
1464 if !full {
1465 let dirty_len: usize = self.get_dirty_paint_nodes().len();
1466 for i in 0..dirty_len {
1467 let nid: NodeId = self.get_dirty_paint_nodes()[i];
1468 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
1469 Some(node) => {
1470 node.get_mut_dirty().remove(clear_mask);
1471 node.parent_id()
1472 }
1473 None => None,
1474 };
1475 while let Some(ancestor_id) = parent_opt {
1476 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1477 if (ancestor.get_dirty().get_bits() & DIRTY_SUBTREE_PAINT) == 0 {
1478 break;
1479 }
1480 ancestor.get_mut_dirty().remove(DIRTY_SUBTREE_PAINT);
1481 parent_opt = ancestor.parent_id();
1482 } else {
1483 break;
1484 }
1485 }
1486 }
1487 self.get_mut_dirty_paint_nodes().clear();
1488 return (region, layout_pending);
1489 }
1490 self.set_full_damage_pending(false);
1491 self.get_mut_dirty_paint_nodes().clear();
1492 for node in self.get_mut_nodes().iter_mut() {
1493 if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
1494 node.get_mut_dirty().remove(clear_mask);
1495 }
1496 }
1497 (DamageRegion::full(), layout_pending)
1498 }
1499
1500 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
1510 let was_overflow: bool = self.get_full_damage_overflow();
1511 self.set_full_damage_overflow(false);
1512 was_overflow
1513 }
1514
1515 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
1526 if id == self.get_root() {
1527 return (Vec::new(), Vec::new());
1528 }
1529 self.record_subtree_logical_damage(id);
1530 self.cancel_subtree_transitions(id);
1531 let mut stack: Vec<NodeId> = vec![id];
1532 let mut scopes: Vec<Scope> = Vec::new();
1533 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1534 while let Some(current) = stack.pop() {
1535 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
1536 Some(node) => {
1537 node.set_alive(false);
1538 if node.has_extras() {
1539 if let Some(scope) = node.owned_scope() {
1540 scopes.push(scope);
1541 }
1542 for hook in node.take_lifecycles().into_iter() {
1543 observers.push((current, hook));
1544 }
1545 node.clear_extras();
1546 }
1547 node.set_parent(None);
1548 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
1549 node.set_generation(next_gen);
1550 Some(take(node.get_mut_children()))
1551 }
1552 None => None,
1553 };
1554 let Some(children) = children_opt else {
1555 continue;
1556 };
1557 let next_live: usize = self.get_live_count().saturating_sub(1);
1558 self.set_live_count(next_live);
1559 if !self.portal_nodes().is_empty() {
1560 self.sync_portal_registration(current, false);
1561 }
1562 if self
1563 .text_selection()
1564 .map(|sel: SelectionState| sel.get_node_id())
1565 == Some(current)
1566 {
1567 self.set_text_selection(None);
1568 }
1569 self.get_mut_free_list().push(current.get_index());
1570 for child in children.into_iter() {
1571 stack.push(child);
1572 }
1573 }
1574 (scopes, observers)
1575 }
1576
1577 pub fn dispose_subtree(&mut self, id: NodeId) {
1584 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
1585 finalize_disposed_subtree(scopes, observers);
1586 }
1587
1588 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
1599 let prev: Option<NodeId> = self.get_focus().focused_node();
1600 if prev == target {
1601 return Vec::new();
1602 }
1603 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
1604 if let Some(old_id) = prev {
1605 if let Some(old_node) = self.get_node_mut(old_id) {
1606 old_node.get_mut_interaction().set_focused(false);
1607 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
1608 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
1609 }
1610 }
1611 self.mark_dirty(old_id, DIRTY_PAINT);
1612 }
1613 self.get_mut_focus().set_focused(target);
1614 if let Some(new_id) = target {
1615 if let Some(new_node) = self.get_node_mut(new_id) {
1616 new_node.get_mut_interaction().set_focused(true);
1617 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
1618 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
1619 }
1620 }
1621 self.mark_dirty(new_id, DIRTY_PAINT);
1622 }
1623 callbacks
1624 }
1625
1626 #[must_use]
1637 pub fn is_node_selectable(&self, id: NodeId) -> bool {
1638 let mut cursor: Option<NodeId> = Some(id);
1639 while let Some(cur) = cursor {
1640 let Some(node) = self.get_node(cur) else {
1641 return false;
1642 };
1643 let text_style: &TextStyle = node.style_ref().text_ref();
1644 if text_style.get_selectable() {
1645 return true;
1646 }
1647 if text_style.get_selectable_explicit() {
1648 return false;
1649 }
1650 cursor = node.parent_id();
1651 }
1652 false
1653 }
1654
1655 #[must_use]
1666 pub fn effective_selection_color(&self, id: NodeId) -> Color {
1667 let mut cursor: Option<NodeId> = Some(id);
1668 while let Some(cur) = cursor {
1669 let Some(node) = self.get_node(cur) else {
1670 break;
1671 };
1672 if let Some(color) = node.style_ref().text_ref().selection_color() {
1673 return color;
1674 }
1675 cursor = node.parent_id();
1676 }
1677 DEFAULT_TEXT_SELECTION_COLOR
1678 }
1679
1680 #[must_use]
1690 pub fn text_selection(&self) -> Option<SelectionState> {
1691 let Self { text_selection, .. } = self;
1692 *text_selection
1693 }
1694
1695 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
1702 let prev: Option<SelectionState> = self.text_selection();
1703 if prev == selection {
1704 return;
1705 }
1706 let Self { text_selection, .. } = self;
1707 *text_selection = selection;
1708 if let Some(old_sel) = prev {
1709 self.mark_dirty(old_sel.get_node_id(), DIRTY_PAINT);
1710 }
1711 if let Some(new_sel) = selection {
1712 self.mark_dirty(new_sel.get_node_id(), DIRTY_PAINT);
1713 }
1714 }
1715
1716 pub fn clear_text_selection(&mut self) {
1722 self.set_text_selection(None);
1723 }
1724
1725 #[must_use]
1735 pub fn get_selected_text(&self) -> Option<String> {
1736 let sel: SelectionState = self.text_selection()?;
1737 if sel.is_empty() {
1738 return None;
1739 }
1740 let node: &SceneNode = self.get_node(sel.get_node_id())?;
1741 let NodeKind::Text(content) = node.get_kind() else {
1742 return None;
1743 };
1744 let extracted: &str = sel.extract_from(content.as_str());
1745 if extracted.is_empty() {
1746 None
1747 } else {
1748 Some(extracted.to_string())
1749 }
1750 }
1751
1752 pub fn select_all_text(&mut self, id: NodeId) -> bool {
1763 if !self.is_node_selectable(id) {
1764 return false;
1765 }
1766 let char_len: Option<usize> = self.get_node(id).and_then(|node: &SceneNode| {
1767 if let NodeKind::Text(content) = node.get_kind() {
1768 Some(content.chars().count())
1769 } else {
1770 None
1771 }
1772 });
1773 let Some(len) = char_len else {
1774 return false;
1775 };
1776 if len == 0 {
1777 return false;
1778 }
1779 self.set_text_selection(Some(SelectionState::new(id, 0, len)));
1780 true
1781 }
1782}
1783
1784impl SceneHandle {
1786 #[must_use]
1792 pub fn new_tree() -> Self {
1793 Self {
1794 inner: Rc::new(RefCell::new(SceneTree::default())),
1795 }
1796 }
1797
1798 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
1807 self.with_write(
1808 |tree: &mut SceneTree| {
1809 tree.set_virtual_scroll(id, scroll_y, content_height);
1810 },
1811 (),
1812 );
1813 }
1814
1815 #[must_use]
1826 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
1827 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
1828 }
1829
1830 pub fn start_transition(&self, transition: NodeTransition) {
1837 self.with_write(
1838 |tree: &mut SceneTree| {
1839 tree.start_transition(transition);
1840 },
1841 (),
1842 );
1843 }
1844
1845 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
1853 self.with_write(
1854 |tree: &mut SceneTree| {
1855 tree.mark_dirty(id, mask);
1856 },
1857 (),
1858 );
1859 }
1860
1861 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
1869 let (scopes, observers): DisposedSubtreePayload = self.with_write(
1870 |tree: &mut SceneTree| {
1871 let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
1872 Some(node) => take(node.get_mut_children()),
1873 None => return (Vec::new(), Vec::new()),
1874 };
1875 let mut all_scopes: Vec<Scope> = Vec::new();
1876 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1877 if new_children.is_empty() {
1878 for old_child in old_children.into_iter() {
1879 let (sc, ob): DisposedSubtreePayload =
1880 tree.dispose_subtree_collect(old_child);
1881 all_scopes.extend(sc);
1882 all_obs.extend(ob);
1883 }
1884 } else if old_children.len() > 16 && new_children.len() > 16 {
1885 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1886 for old_child in old_children.into_iter() {
1887 if !keep_set.contains(&old_child) {
1888 let (sc, ob): DisposedSubtreePayload =
1889 tree.dispose_subtree_collect(old_child);
1890 all_scopes.extend(sc);
1891 all_obs.extend(ob);
1892 }
1893 }
1894 } else {
1895 for old_child in old_children.into_iter() {
1896 if !new_children.contains(&old_child) {
1897 let (sc, ob): DisposedSubtreePayload =
1898 tree.dispose_subtree_collect(old_child);
1899 all_scopes.extend(sc);
1900 all_obs.extend(ob);
1901 }
1902 }
1903 }
1904 for child in new_children.iter().copied() {
1905 if let Some(child_node) = tree.get_node_mut(child) {
1906 child_node.set_parent(Some(parent));
1907 }
1908 }
1909 if let Some(parent_node) = tree.get_node_mut(parent) {
1910 parent_node.set_children(new_children);
1911 }
1912 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1913 (all_scopes, all_obs)
1914 },
1915 (Vec::new(), Vec::new()),
1916 );
1917 finalize_disposed_subtree(scopes, observers);
1918 }
1919
1920 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
1928 let (scopes, observers): DisposedSubtreePayload = self.with_write(
1929 |tree: &mut SceneTree| {
1930 if let Some(pnode) = tree.get_node_mut(parent) {
1931 pnode.get_mut_children().retain(|id: &NodeId| *id != child);
1932 }
1933 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
1934 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1935 out
1936 },
1937 (Vec::new(), Vec::new()),
1938 );
1939 finalize_disposed_subtree(scopes, observers);
1940 }
1941
1942 pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
1954 where
1955 F: FnOnce(&mut Style),
1956 {
1957 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
1958 }
1959
1960 pub fn freeze_subtree(&self, root: NodeId) {
1967 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1968 |tree: &mut SceneTree| {
1969 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
1970 tree.cancel_subtree_transitions(root);
1971 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
1972 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
1973 if layout.get_display() == Display::None {
1974 false
1975 } else {
1976 layout.set_display(Display::None);
1977 true
1978 }
1979 } else {
1980 false
1981 };
1982 if changed {
1983 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1984 }
1985 obs
1986 },
1987 Vec::new(),
1988 );
1989 dispatch_lifecycle_freeze(&observers);
1990 }
1991
1992 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
2000 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2001 |tree: &mut SceneTree| {
2002 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
2003 tree.cancel_subtree_transitions(root);
2004 let mut demoted_fixed: bool = false;
2005 if let Some(node) = tree.get_node_mut(root) {
2006 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
2007 let st: &mut Style = node.get_mut_style();
2008 demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
2009 st.get_mut_layout()
2010 .set_position(Position::Absolute)
2011 .set_top(Some(0.0))
2012 .set_right(Some(0.0))
2013 .set_bottom(None)
2014 .set_left(Some(0.0))
2015 .set_z_index(0);
2016 st.get_mut_paint().set_pointer_events(PointerEvents::None);
2017 }
2018 if demoted_fixed {
2019 tree.sync_portal_registration(root, false);
2020 }
2021 tree.start_transition(exit_transition.with_hide_on_complete(true));
2022 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2023 obs
2024 },
2025 Vec::new(),
2026 );
2027 dispatch_lifecycle_freeze(&observers);
2028 }
2029
2030 pub fn resume_subtree(&self, root: NodeId) {
2037 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2038 |tree: &mut SceneTree| {
2039 let mut unhidden: bool = false;
2040 if let Some(node) = tree.get_node_mut(root) {
2041 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
2042 if layout.get_display() == Display::None {
2043 layout.set_display(Display::Flex);
2044 unhidden = true;
2045 }
2046 }
2047 if unhidden {
2048 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2049 } else {
2050 tree.mark_dirty(root, DIRTY_PAINT);
2051 }
2052 tree.collect_subtree_lifecycles(root)
2053 },
2054 Vec::new(),
2055 );
2056 dispatch_lifecycle_resume(&observers);
2057 }
2058
2059 pub fn activate_subtree(&self, root: NodeId) {
2066 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2067 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2068 Vec::new(),
2069 );
2070 dispatch_lifecycle_activate(&observers);
2071 }
2072
2073 pub fn update_subtree(&self, root: NodeId) {
2080 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2081 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2082 Vec::new(),
2083 );
2084 dispatch_lifecycle_update(&observers);
2085 }
2086
2087 pub fn emit_subtree_appear(&self, root: NodeId) {
2094 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2095 |tree: &SceneTree| {
2096 (
2097 tree.collect_subtree_lifecycles(root),
2098 tree.collect_subtree_scope_ids(root),
2099 )
2100 },
2101 (Vec::new(), Vec::new()),
2102 );
2103 let ev: SystemEvent = SystemEvent::Appear;
2104 dispatch_lifecycle_system_event(&observers, &ev);
2105 dispatch_system_event_to_scopes(&scopes, &ev);
2106 }
2107
2108 pub fn emit_subtree_disappear(&self, root: NodeId) {
2115 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2116 |tree: &SceneTree| {
2117 (
2118 tree.collect_subtree_lifecycles(root),
2119 tree.collect_subtree_scope_ids(root),
2120 )
2121 },
2122 (Vec::new(), Vec::new()),
2123 );
2124 let ev: SystemEvent = SystemEvent::Disappear;
2125 dispatch_lifecycle_system_event(&observers, &ev);
2126 dispatch_system_event_to_scopes(&scopes, &ev);
2127 }
2128
2129 #[must_use]
2139 pub fn has_active_transitions(&self) -> bool {
2140 self.with_read(SceneTree::has_active_transitions, false)
2141 }
2142
2143 #[must_use]
2153 pub fn get_selected_text(&self) -> Option<String> {
2154 self.with_read(SceneTree::get_selected_text, None)
2155 }
2156
2157 pub fn clear_text_selection(&self) {
2163 self.with_write(SceneTree::clear_text_selection, ());
2164 }
2165
2166 pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
2178 where
2179 F: FnOnce(&SceneTree) -> R,
2180 {
2181 let Self { inner } = self;
2182 match inner.try_borrow() {
2183 Ok(guard) => operation(&guard),
2184 Err(_) => fallback,
2185 }
2186 }
2187
2188 pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
2200 where
2201 F: FnOnce(&mut SceneTree) -> R,
2202 {
2203 let Self { inner } = self;
2204 match inner.try_borrow_mut() {
2205 Ok(mut guard) => operation(&mut guard),
2206 Err(_) => fallback,
2207 }
2208 }
2209
2210 pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2222 where
2223 F: FnMut() -> String + 'static,
2224 {
2225 let handle: Self = self.clone();
2226 Effect::new(move || {
2227 let value: String = producer();
2228 handle.with_write(
2229 |tree: &mut SceneTree| {
2230 tree.set_text(node_id, value);
2231 },
2232 (),
2233 );
2234 })
2235 }
2236
2237 pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2249 where
2250 F: FnMut() -> Style + 'static,
2251 {
2252 let handle: Self = self.clone();
2253 Effect::new(move || {
2254 let style: Style = producer();
2255 handle.with_write(
2256 |tree: &mut SceneTree| {
2257 tree.set_style(node_id, style);
2258 },
2259 (),
2260 );
2261 })
2262 }
2263}
2264
2265impl Context {
2267 #[must_use]
2278 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
2279 Self {
2280 scene,
2281 breakpoint: Signal::new(Breakpoint::Expanded),
2282 viewport_size: Signal::new(Size::new(1200.0, 800.0)),
2283 theme_mode: Signal::new(ThemeMode::Light),
2284 platform,
2285 safe_area: Signal::new(SafeAreaInsets::default()),
2286 gesture: Signal::new(None),
2287 swipe_drag_offset: Signal::new(0.0),
2288 system_back: Signal::new(0),
2289 dynamic_hub: DynamicUpdateHub::new(),
2290 fps_limit: Signal::new(None),
2291 live_fps: Signal::new(60.0),
2292 present_fps: Signal::new(0.0),
2293 is_idle: Signal::new(true),
2294 display_refresh_rate: Signal::new(60.0),
2295 active_touches: Signal::new(Vec::new()),
2296 exit_requested: Signal::new(false),
2297 app_state: Signal::new(AppState::Active),
2298 network_status: Signal::new(NetworkStatus::Online),
2299 keyboard_visible: Signal::new(false),
2300 keyboard_height: Signal::new(0.0),
2301 orientation: Signal::new(ScreenOrientation::Landscape),
2302 low_power_mode: Signal::new(false),
2303 locale: Signal::new(DEFAULT_SYSTEM_LOCALE.to_string()),
2304 window_focused: Signal::new(true),
2305 clock_ms: Rc::new(Cell::new(0)),
2306 }
2307 }
2308
2309 #[must_use]
2319 pub fn app_state_signal(&self) -> Signal<AppState> {
2320 self.get_app_state()
2321 }
2322
2323 pub fn emit_page_appear(&self) {
2329 let ev: SystemEvent = SystemEvent::Appear;
2330 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2331 .get_scene()
2332 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2333 dispatch_lifecycle_system_event(&observers, &ev);
2334 dispatch_system_event_listeners(&ev);
2335 }
2336
2337 pub fn emit_page_disappear(&self) {
2343 let ev: SystemEvent = SystemEvent::Disappear;
2344 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2345 .get_scene()
2346 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2347 dispatch_lifecycle_system_event(&observers, &ev);
2348 dispatch_system_event_listeners(&ev);
2349 }
2350
2351 pub fn emit_subtree_appear(&self, root: NodeId) {
2358 self.get_scene().emit_subtree_appear(root);
2359 }
2360
2361 pub fn emit_subtree_disappear(&self, root: NodeId) {
2368 self.get_scene().emit_subtree_disappear(root);
2369 }
2370
2371 #[must_use]
2381 pub fn elapsed_ms(&self) -> u64 {
2382 let Self { clock_ms, .. } = self;
2383 clock_ms.get()
2384 }
2385
2386 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
2393 let Self { clock_ms, .. } = self;
2394 clock_ms.set(clock_ms.get().saturating_add(delta_ms));
2395 }
2396
2397 pub fn request_exit(&self) {
2403 let _: bool = self.get_exit_requested().set_if_changed(true);
2404 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
2405 }
2406
2407 pub fn copy_to_clipboard(&self, text: &str) -> bool {
2418 write_system_clipboard(text)
2419 }
2420
2421 pub fn view(&mut self, style: Style) -> NodeId {
2432 self.get_scene().with_write(
2433 |tree: &mut SceneTree| tree.create_view(style),
2434 NodeId::default(),
2435 )
2436 }
2437
2438 pub fn text(&mut self, content: String, style: Style) -> NodeId {
2450 self.get_scene().with_write(
2451 |tree: &mut SceneTree| tree.create_text(content, style),
2452 NodeId::default(),
2453 )
2454 }
2455
2456 pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
2468 where
2469 F: FnMut() -> String + 'static,
2470 {
2471 let node_id: NodeId = self.text(String::new(), style);
2472 let handle: SceneHandle = self.get_scene().clone();
2473 let (scope, _): (Scope, Effect) =
2474 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
2475 self.get_scene().with_write(
2476 |tree: &mut SceneTree| {
2477 tree.attach_scope(node_id, scope);
2478 },
2479 (),
2480 );
2481 node_id
2482 }
2483
2484 pub fn scroll_view(&mut self, style: Style) -> NodeId {
2495 self.get_scene().with_write(
2496 |tree: &mut SceneTree| tree.create_scroll_view(style),
2497 NodeId::default(),
2498 )
2499 }
2500
2501 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
2513 self.get_scene().with_write(
2514 |tree: &mut SceneTree| tree.create_input(state, style),
2515 NodeId::default(),
2516 )
2517 }
2518
2519 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
2531 self.get_scene().with_write(
2532 |tree: &mut SceneTree| tree.create_image(buffer, style),
2533 NodeId::default(),
2534 )
2535 }
2536
2537 pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
2549 where
2550 F: FnMut(Rect, &mut DisplayList) + 'static,
2551 {
2552 let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
2553 self.get_scene().with_write(
2554 |tree: &mut SceneTree| tree.create_canvas(style, cb),
2555 NodeId::default(),
2556 )
2557 }
2558
2559 pub fn portal(&mut self, style: Style) -> NodeId {
2570 self.get_scene().with_write(
2571 |tree: &mut SceneTree| tree.create_portal(style),
2572 NodeId::default(),
2573 )
2574 }
2575
2576 pub fn fragment(&mut self) -> NodeId {
2586 self.get_scene().with_write(
2587 |tree: &mut SceneTree| tree.create_fragment(),
2588 NodeId::default(),
2589 )
2590 }
2591
2592 pub fn append(&mut self, parent: NodeId, child: NodeId) {
2600 self.get_scene().with_write(
2601 |tree: &mut SceneTree| {
2602 tree.append_child(parent, child);
2603 },
2604 (),
2605 );
2606 }
2607
2608 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
2616 if children.is_empty() {
2617 return;
2618 }
2619 self.get_scene().with_write(
2620 |tree: &mut SceneTree| {
2621 tree.append_children(parent, children);
2622 },
2623 (),
2624 );
2625 }
2626
2627 pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
2635 where
2636 F: FnMut() -> Style + 'static,
2637 {
2638 let handle: SceneHandle = self.get_scene().clone();
2639 let (scope, _): (Scope, Effect) =
2640 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
2641 self.get_scene().with_write(
2642 |tree: &mut SceneTree| {
2643 tree.attach_scope(node_id, scope);
2644 },
2645 (),
2646 );
2647 }
2648
2649 pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
2657 where
2658 F: FnMut(&UiEvent) + 'static,
2659 {
2660 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2661 self.get_scene().with_write(
2662 |tree: &mut SceneTree| {
2663 if let Some(node) = tree.get_node_mut(node_id) {
2664 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
2665 }
2666 },
2667 (),
2668 );
2669 }
2670
2671 pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
2679 where
2680 F: FnMut(&UiEvent) + 'static,
2681 {
2682 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2683 self.get_scene().with_write(
2684 |tree: &mut SceneTree| {
2685 if let Some(node) = tree.get_node_mut(node_id) {
2686 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
2687 }
2688 },
2689 (),
2690 );
2691 }
2692
2693 pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
2701 where
2702 F: FnMut(&UiEvent) + 'static,
2703 {
2704 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2705 self.get_scene().with_write(
2706 |tree: &mut SceneTree| {
2707 if let Some(node) = tree.get_node_mut(node_id) {
2708 node.get_mut_handlers().set_on_focus(Some(handler));
2709 node.get_mut_interaction().set_focusable(true);
2710 }
2711 },
2712 (),
2713 );
2714 }
2715
2716 pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
2724 where
2725 F: FnMut(&UiEvent) + 'static,
2726 {
2727 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2728 self.get_scene().with_write(
2729 |tree: &mut SceneTree| {
2730 if let Some(node) = tree.get_node_mut(node_id) {
2731 node.get_mut_handlers().set_on_blur(Some(handler));
2732 }
2733 },
2734 (),
2735 );
2736 }
2737
2738 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
2746 self.get_scene().with_write(
2747 |tree: &mut SceneTree| {
2748 if let Some(node) = tree.get_node_mut(node_id) {
2749 node.get_mut_interaction().set_focusable(focusable);
2750 }
2751 },
2752 (),
2753 );
2754 }
2755
2756 pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
2764 where
2765 F: FnMut(&UiEvent) + 'static,
2766 {
2767 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2768 self.get_scene().with_write(
2769 |tree: &mut SceneTree| {
2770 if let Some(node) = tree.get_node_mut(node_id) {
2771 node.get_mut_handlers().set_on_click(Some(handler));
2772 node.get_mut_interaction().set_focusable(true);
2773 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
2774 if paint.get_cursor() == CursorIcon::Default {
2775 paint.set_cursor(CursorIcon::Pointer);
2776 }
2777 }
2778 },
2779 (),
2780 );
2781 }
2782
2783 pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
2791 where
2792 F: FnMut(&UiEvent) + 'static,
2793 {
2794 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2795 self.get_scene().with_write(
2796 |tree: &mut SceneTree| {
2797 if let Some(node) = tree.get_node_mut(node_id) {
2798 node.get_mut_handlers().set_on_change(Some(handler));
2799 }
2800 },
2801 (),
2802 );
2803 }
2804
2805 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
2813 self.get_scene().with_write(
2814 |tree: &mut SceneTree| {
2815 if let Some(node) = tree.get_node_mut(node_id) {
2816 node.set_a11y(Some(props));
2817 }
2818 },
2819 (),
2820 );
2821 }
2822
2823 pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
2831 where
2832 F: FnMut(&UiEvent) + 'static,
2833 {
2834 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2835 self.get_scene().with_write(
2836 |tree: &mut SceneTree| {
2837 if let Some(node) = tree.get_node_mut(node_id) {
2838 node.get_mut_handlers().set_on_scroll(Some(handler));
2839 }
2840 },
2841 (),
2842 );
2843 }
2844
2845 pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
2853 where
2854 F: FnMut(&UiEvent) + 'static,
2855 {
2856 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2857 self.get_scene().with_write(
2858 |tree: &mut SceneTree| {
2859 if let Some(node) = tree.get_node_mut(node_id) {
2860 node.get_mut_handlers().set_on_pointer_down(Some(handler));
2861 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
2862 if paint.get_cursor() == CursorIcon::Default {
2863 paint.set_cursor(CursorIcon::Pointer);
2864 }
2865 }
2866 },
2867 (),
2868 );
2869 }
2870
2871 pub fn on_pointer_move<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_pointer_move(Some(handler));
2887 }
2888 },
2889 (),
2890 );
2891 }
2892
2893 pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
2901 where
2902 F: FnMut(&UiEvent) + 'static,
2903 {
2904 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2905 self.get_scene().with_write(
2906 |tree: &mut SceneTree| {
2907 if let Some(node) = tree.get_node_mut(node_id) {
2908 node.get_mut_handlers().set_on_pointer_up(Some(handler));
2909 }
2910 },
2911 (),
2912 );
2913 }
2914
2915 pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
2923 where
2924 F: FnMut(&UiEvent) + 'static,
2925 {
2926 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2927 let leave_handler: UiEventHandler = handler.clone();
2928 self.get_scene().with_write(
2929 |tree: &mut SceneTree| {
2930 if let Some(node) = tree.get_node_mut(node_id) {
2931 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
2932 node.get_mut_handlers()
2933 .set_on_pointer_leave(Some(leave_handler));
2934 }
2935 },
2936 (),
2937 );
2938 }
2939
2940 pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
2948 where
2949 F: FnMut(&UiEvent) + 'static,
2950 {
2951 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2952 self.get_scene().with_write(
2953 |tree: &mut SceneTree| {
2954 if let Some(node) = tree.get_node_mut(node_id) {
2955 node.get_mut_handlers().set_on_key_down(Some(handler));
2956 node.get_mut_interaction().set_focusable(true);
2957 }
2958 },
2959 (),
2960 );
2961 }
2962
2963 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
2972 self.get_scene()
2973 .set_virtual_scroll(node_id, scroll_y, content_height);
2974 }
2975
2976 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
2984 self.get_scene().with_write(
2985 |tree: &mut SceneTree| {
2986 tree.set_scroll_offset(node_id, offset);
2987 },
2988 (),
2989 );
2990 }
2991
2992 pub fn start_transition(&mut self, transition: NodeTransition) {
2999 self.get_scene().start_transition(transition);
3000 }
3001
3002 pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
3010 where
3011 F: FnMut() -> Vec<NodeId> + 'static,
3012 {
3013 let ctx_clone: Self = self.clone();
3014 let handle: SceneHandle = self.get_scene().clone();
3015 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3016 Effect::new(move || {
3017 let (child_scope, children): (Scope, Vec<NodeId>) =
3018 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
3019 let first_opt: Option<NodeId> = children.first().copied();
3020 handle.replace_children_safe(host, children);
3021 if let Some(first) = first_opt {
3022 handle.with_write(
3023 |tree: &mut SceneTree| {
3024 tree.attach_scope(first, child_scope);
3025 },
3026 (),
3027 );
3028 }
3029 })
3030 });
3031 self.get_scene().with_write(
3032 |tree: &mut SceneTree| {
3033 tree.attach_scope(host, scope);
3034 },
3035 (),
3036 );
3037 }
3038}
3039
3040impl Drop for ContextGuard {
3042 fn drop(&mut self) {
3048 let Self { previous } = self;
3049 let restored: Option<Context> = previous.take();
3050 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
3051 *slot.borrow_mut() = restored;
3052 });
3053 }
3054}
3055
3056impl NodeRefTarget for NodeId {
3058 fn bind_node_ref(&mut self, id: NodeId) {
3065 *self = id;
3066 }
3067}
3068
3069impl NodeRefTarget for Option<NodeId> {
3071 fn bind_node_ref(&mut self, id: NodeId) {
3078 *self = Some(id);
3079 }
3080}
3081
3082impl NodeRefTarget for Cell<NodeId> {
3084 fn bind_node_ref(&mut self, id: NodeId) {
3091 self.set(id);
3092 }
3093}
3094
3095impl NodeRefTarget for Rc<Cell<NodeId>> {
3097 fn bind_node_ref(&mut self, id: NodeId) {
3104 self.set(id);
3105 }
3106}
3107
3108impl NodeRefTarget for Cell<Option<NodeId>> {
3110 fn bind_node_ref(&mut self, id: NodeId) {
3117 self.set(Some(id));
3118 }
3119}
3120
3121impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
3123 fn bind_node_ref(&mut self, id: NodeId) {
3130 self.set(Some(id));
3131 }
3132}
3133
3134impl TextNodeContent for String {
3136 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3148 ctx.text(self, style)
3149 }
3150}
3151
3152impl TextNodeContent for &str {
3154 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3166 ctx.text(self.to_string(), style)
3167 }
3168}
3169
3170impl TextNodeContent for &String {
3172 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3184 ctx.text(self.clone(), style)
3185 }
3186}
3187
3188impl TextNodeContent for Cow<'_, str> {
3190 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3202 ctx.text(self.into_owned(), style)
3203 }
3204}
3205
3206impl<F, S> TextNodeContent for F
3208where
3209 F: FnMut() -> S + 'static,
3210 S: Into<String>,
3211{
3212 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
3224 ctx.reactive_text(style, move || self().into())
3225 }
3226}