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 backdrop_blur_nodes: Vec::new(),
34 layout_invalidations: 1,
35 last_collect_composite_only: false,
36 }
37 }
38}
39
40impl SceneTree {
42 pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
50 if self.get_node(id).is_none() {
51 return;
52 }
53 let clamped: f32 = if blur_radius.is_finite() {
54 blur_radius.clamp(0.0, 96.0)
55 } else {
56 0.0
57 };
58 let prev_radius: f32 = self.backdrop_blur_radius(id);
59 if (prev_radius - clamped).abs() <= 0.001 {
60 return;
61 }
62 if prev_radius > 0.0 {
63 self.record_node_logical_damage(id);
64 }
65 let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
66 if clamped <= 0.0 {
67 blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
68 } else if let Some(slot) = blurs
69 .iter_mut()
70 .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
71 {
72 slot.1 = clamped;
73 } else {
74 blurs.push((id, clamped));
75 }
76 self.mark_dirty(id, DIRTY_PAINT);
77 }
78
79 #[must_use]
90 pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
91 for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
92 if nid == id {
93 return radius;
94 }
95 }
96 0.0
97 }
98
99 #[must_use]
109 pub fn has_backdrop_blur_nodes(&self) -> bool {
110 !self.get_backdrop_blur_nodes().is_empty()
111 }
112
113 pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
125 if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
126 return 0;
127 }
128 let clamped_scale: f32 = scale.max(0.5);
129 let blur_count: usize = self.get_backdrop_blur_nodes().len();
130 let mut dirtied: Vec<bool> = vec![false; blur_count];
131 let mut total_added: usize = 0;
132 let mut changed: bool = true;
133 while changed && !damage.get_full_damage() {
134 changed = false;
135 if damage.bounds_rect().is_none() {
136 break;
137 }
138 for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
139 if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
140 continue;
141 }
142 let Some(screen_rect) = self.node_screen_bounds(nid) else {
143 continue;
144 };
145 if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
146 continue;
147 }
148 let sigma: f32 = (blur_radius * 0.5).max(0.75);
149 let halo: f32 = (sigma * 3.0).ceil() + 2.0;
150 let sample_logical: Rect = Rect::new(
151 screen_rect.get_x() - halo,
152 screen_rect.get_y() - halo,
153 screen_rect.get_width() + halo * 2.0,
154 screen_rect.get_height() + halo * 2.0,
155 );
156 let sample_phys: Rect =
157 Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
158 let output_phys: Rect = Self::scale_logical_to_phys_rect(
159 Rect::new(
160 screen_rect.get_x() - 2.0,
161 screen_rect.get_y() - 2.0,
162 screen_rect.get_width() + 4.0,
163 screen_rect.get_height() + 4.0,
164 ),
165 clamped_scale,
166 );
167 let (rects, count): ([Rect; 8], usize) =
168 damage.normalized_rects(u32::MAX, u32::MAX);
169 let overlaps: bool = rects
170 .iter()
171 .take(count)
172 .any(|r: &Rect| r.intersect(sample_phys).is_some());
173 if overlaps {
174 damage.add_rect(output_phys);
175 dirtied[idx] = true;
176 total_added += 1;
177 changed = true;
178 }
179 }
180 }
181 total_added
182 }
183 #[must_use]
193 #[inline(always)]
194 pub fn portal_nodes(&self) -> &[NodeId] {
195 let Self { portal_nodes, .. } = self;
196 portal_nodes.as_slice()
197 }
198
199 #[must_use]
209 #[inline(always)]
210 pub fn has_portal_nodes(&self) -> bool {
211 let Self { portal_nodes, .. } = self;
212 !portal_nodes.is_empty()
213 }
214
215 fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
223 let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
224 if is_portal {
225 if !portals.contains(&id) {
226 portals.push(id);
227 }
228 } else if !portals.is_empty() {
229 portals.retain(|existing: &NodeId| *existing != id);
230 }
231 }
232
233 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
245 let is_portal: bool = matches!(kind, NodeKind::Portal)
246 || style.get_layout().get_position() == Position::Fixed;
247 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
248 let slot: &mut SceneNode = &mut self.get_mut_nodes()[index as usize];
249 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
250 *slot = SceneNode::new(next_gen, kind, style);
251 NodeId::new(index, next_gen)
252 } else {
253 let index: u32 = self.get_nodes().len() as u32;
254 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
255 NodeId::new(index, 1)
256 };
257 if is_portal {
258 self.get_mut_portal_nodes().push(id);
259 self.set_full_damage_pending(true);
260 }
261 let next_live: usize = self.get_live_count().saturating_add(1);
262 self.set_live_count(next_live);
263 let next_created: usize = self.get_created_since_damage().saturating_add(1);
264 self.set_created_since_damage(next_created);
265 self.set_layout_damage_pending(true);
266 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
267 if next_created > DIRTY_PAINT_FULL_THRESHOLD {
268 self.set_full_damage_pending(true);
269 self.set_full_damage_overflow(true);
270 self.get_mut_dirty_paint_nodes().clear();
271 } else if !self.get_full_damage_pending() {
272 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
273 self.set_full_damage_pending(true);
274 self.set_full_damage_overflow(true);
275 self.get_mut_dirty_paint_nodes().clear();
276 } else {
277 self.get_mut_dirty_paint_nodes().push(id);
278 }
279 }
280 let next_rev: u64 = self.get_revision().wrapping_add(1);
281 self.set_revision(next_rev);
282 id
283 }
284
285 pub fn create_view(&mut self, style: Style) -> NodeId {
296 self.create_node(NodeKind::View, style)
297 }
298
299 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
311 self.create_node(NodeKind::Text(content), style)
312 }
313
314 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
326 self.create_node(NodeKind::Input(state), style)
327 }
328
329 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
341 self.create_node(NodeKind::Image(buffer), style)
342 }
343
344 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
355 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
356 }
357
358 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
370 let id: NodeId = self.create_node(NodeKind::Canvas, style);
371 if let Some(node) = self.get_node_mut(id) {
372 node.set_canvas_painter(Some(painter));
373 }
374 id
375 }
376
377 pub fn create_portal(&mut self, style: Style) -> NodeId {
388 self.create_node(NodeKind::Portal, style)
389 }
390
391 pub fn create_fragment(&mut self) -> NodeId {
401 self.create_node(NodeKind::Fragment, Style::default())
402 }
403
404 #[must_use]
415 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
416 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
417 if node.get_alive() && node.get_generation() == id.get_generation() {
418 Some(node)
419 } else {
420 None
421 }
422 }
423
424 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
435 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
436 if node.get_alive() && node.get_generation() == id.get_generation() {
437 Some(node)
438 } else {
439 None
440 }
441 }
442
443 #[must_use]
453 #[inline(always)]
454 pub fn live_node_count(&self) -> usize {
455 self.get_live_count()
456 }
457
458 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
466 if parent == child {
467 return;
468 }
469 let prev_parent: Option<NodeId> = self.get_node(child).and_then(SceneNode::parent_id);
470 if let Some(old_parent) = prev_parent {
471 if old_parent != parent {
472 self.record_subtree_logical_damage(child);
473 }
474 if let Some(old_node) = self.get_node_mut(old_parent) {
475 old_node
476 .get_mut_children()
477 .retain(|item: &NodeId| *item != child);
478 if old_parent != parent {
479 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
480 }
481 }
482 }
483 if let Some(child_node) = self.get_node_mut(child) {
484 child_node.set_parent(Some(parent));
485 } else {
486 return;
487 }
488 if let Some(parent_node) = self.get_node_mut(parent) {
489 parent_node.get_mut_children().push(child);
490 }
491 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
492 }
493
494 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
502 if children.is_empty() || self.get_node(parent).is_none() {
503 return;
504 }
505 let all_fresh_orphans: bool = children.iter().copied().all(|child: NodeId| {
506 child != parent
507 && self
508 .get_node(child)
509 .is_some_and(|node: &SceneNode| node.parent_id().is_none())
510 });
511 if all_fresh_orphans {
512 for child in children.iter().copied() {
513 if let Some(child_node) = self.get_node_mut(child) {
514 child_node.set_parent(Some(parent));
515 }
516 }
517 if let Some(parent_node) = self.get_node_mut(parent) {
518 parent_node.get_mut_children().extend_from_slice(children);
519 }
520 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
521 return;
522 }
523 let mut attached: Vec<NodeId> = Vec::with_capacity(children.len());
524 for child in children.iter().copied() {
525 if child == parent {
526 continue;
527 }
528 let prev_parent: Option<NodeId> = self
529 .get_node(child)
530 .and_then(|node: &SceneNode| node.parent_id());
531 if let Some(old_parent) = prev_parent {
532 if old_parent != parent {
533 self.record_subtree_logical_damage(child);
534 }
535 if let Some(old_node) = self.get_node_mut(old_parent) {
536 old_node
537 .get_mut_children()
538 .retain(|id: &NodeId| *id != child);
539 }
540 if old_parent != parent {
541 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
542 }
543 }
544 if let Some(child_node) = self.get_node_mut(child) {
545 child_node.set_parent(Some(parent));
546 attached.push(child);
547 }
548 }
549 if attached.is_empty() {
550 return;
551 }
552 if let Some(parent_node) = self.get_node_mut(parent) {
553 parent_node.get_mut_children().extend(attached);
554 }
555 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
556 }
557
558 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
566 let old_children: Vec<NodeId> = match self.get_node_mut(parent) {
567 Some(node) => take(node.get_mut_children()),
568 None => return,
569 };
570 if new_children.is_empty() {
571 for old_child in old_children.into_iter() {
572 self.dispose_subtree(old_child);
573 }
574 } else if old_children.len() > 16 && new_children.len() > 16 {
575 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
576 for old_child in old_children.into_iter() {
577 if !keep_set.contains(&old_child) {
578 self.dispose_subtree(old_child);
579 }
580 }
581 } else {
582 for old_child in old_children.into_iter() {
583 if !new_children.contains(&old_child) {
584 self.dispose_subtree(old_child);
585 }
586 }
587 }
588 for child in new_children.iter().copied() {
589 if let Some(child_node) = self.get_node_mut(child) {
590 child_node.set_parent(Some(parent));
591 }
592 }
593 if let Some(parent_node) = self.get_node_mut(parent) {
594 parent_node.set_children(new_children);
595 }
596 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
597 }
598
599 #[inline]
610 fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
611 let same_static: bool = prev.background_color() == next.background_color()
612 && prev.background_gradient() == next.background_gradient()
613 && prev.get_border() == next.get_border()
614 && prev.get_radius() == next.get_radius()
615 && prev.box_shadow() == next.box_shadow()
616 && prev.focus_ring_border() == next.focus_ring_border()
617 && prev.get_cursor() == next.get_cursor()
618 && prev.get_pointer_events() == next.get_pointer_events();
619 let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
620 let composite_changed: bool = prev.get_transform() != next.get_transform()
621 || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
622 same_static && same_vis && composite_changed
623 }
624
625 #[inline]
637 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
638 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
639 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
640 if layout_changed || text_metrics_changed {
641 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
642 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
643 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
644 Some(next_fixed)
645 } else {
646 None
647 };
648 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
649 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
650 let mask: u16 = layout_bits | visual_bits;
651 return (mask, portal_update);
652 }
653 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
654 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
655 if paint_changed && !text_visual_changed {
656 if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
657 return (DIRTY_COMPOSITE, None);
658 }
659 return (DIRTY_PAINT, None);
660 }
661 if paint_changed || text_visual_changed {
662 (DIRTY_PAINT, None)
663 } else {
664 (DIRTY_NONE, None)
665 }
666 }
667
668 #[inline]
679 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
680 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
681 let transform_changed: bool = prev.get_transform() != next.get_transform();
682 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
683 let focus_removed: bool =
684 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
685 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
686 let a: bool = shadow_changed || transform_changed;
687 let b: bool = border_shrank || focus_removed;
688 let ab: bool = a || b;
689 ab || opacity_toggled_zero
690 }
691
692 pub fn set_style(&mut self, id: NodeId, style: Style) {
700 let pre_snapshot: Option<(u16, Option<bool>, bool, bool)> =
701 self.get_node(id).map(|node: &SceneNode| {
702 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
703 let prev: &Style = node.style_ref();
704 let (mask, update): (u16, Option<bool>) =
705 Self::diff_style_change(prev, &style, is_portal_kind);
706 let pre_paint: bool = mask != DIRTY_NONE
707 && Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
708 let subtree_hidden: bool = pre_paint
709 && (prev.paint_ref().get_opacity() > 0.0)
710 != (style.paint_ref().get_opacity() > 0.0)
711 && !node.get_children().is_empty();
712 (mask, update, pre_paint, subtree_hidden)
713 });
714 let Some((dirty_mask, portal_update, pre_paint, subtree_hidden)) = pre_snapshot else {
715 return;
716 };
717 if dirty_mask == DIRTY_NONE {
718 return;
719 }
720 if subtree_hidden {
721 self.record_subtree_logical_damage(id);
722 } else if pre_paint {
723 self.record_node_logical_damage(id);
724 }
725 let hiding_now: bool = style.layout_ref().get_display() == Display::None
726 || style.paint_ref().get_opacity() <= 0.001
727 || style.paint_ref().get_pointer_events() == PointerEvents::None;
728 if let Some(node) = self.get_node_mut(id) {
729 node.set_style(style);
730 }
731 if hiding_now {
732 self.clear_subtree_hover(id);
733 }
734 if let Some(is_portal) = portal_update {
735 self.sync_portal_registration(id, is_portal);
736 }
737 self.mark_dirty(id, dirty_mask);
738 }
739
740 pub fn mutate_style<F>(&mut self, id: NodeId, mutator: F) -> bool
752 where
753 F: FnOnce(&mut Style),
754 {
755 let prev_opt: Option<(Style, bool, bool)> = self.get_node(id).map(|node: &SceneNode| {
756 (
757 *node.style_ref(),
758 matches!(node.get_kind(), NodeKind::Portal),
759 !node.get_children().is_empty(),
760 )
761 });
762 let Some((prev, is_portal_kind, has_children)) = prev_opt else {
763 return false;
764 };
765 let mut next: Style = prev;
766 mutator(&mut next);
767 let (dirty_mask, portal_update): (u16, Option<bool>) =
768 Self::diff_style_change(&prev, &next, is_portal_kind);
769 if dirty_mask == DIRTY_NONE {
770 return false;
771 }
772 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
773 if pre_paint {
774 let opacity_toggled_zero: bool =
775 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
776 if opacity_toggled_zero && has_children {
777 self.record_subtree_logical_damage(id);
778 } else {
779 self.record_node_logical_damage(id);
780 }
781 }
782 let hiding_now: bool = next.layout_ref().get_display() == Display::None
783 || next.paint_ref().get_opacity() <= 0.001
784 || next.paint_ref().get_pointer_events() == PointerEvents::None;
785 if let Some(node) = self.get_node_mut(id) {
786 node.set_style(next);
787 }
788 if hiding_now {
789 self.clear_subtree_hover(id);
790 }
791 if let Some(is_portal) = portal_update {
792 self.sync_portal_registration(id, is_portal);
793 }
794 self.mark_dirty(id, dirty_mask);
795 true
796 }
797
798 pub fn set_text(&mut self, id: NodeId, text: String) {
806 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
807 Some(node) => {
808 let layout: &LayoutStyle = node.style_ref().layout_ref();
809 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
810 && matches!(layout.get_height(), Length::Px(_));
811 match node.get_mut_kind() {
812 NodeKind::Text(current) => {
813 if *current == text {
814 (false, has_fixed)
815 } else {
816 *current = text;
817 (true, has_fixed)
818 }
819 }
820 _ => (false, false),
821 }
822 }
823 None => (false, false),
824 };
825 if changed {
826 let mask: u16 = if fixed_size {
827 DIRTY_PAINT
828 } else {
829 DIRTY_TEXT_CHANGE_MASK
830 };
831 self.mark_dirty(id, mask);
832 }
833 }
834
835 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
843 let changed: bool = match self.get_node_mut(id) {
844 Some(node) => {
845 let layout_box: LayoutBox = node.get_layout_box();
846 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
847 && layout_box.get_content_size().get_height() <= 0.0
848 && layout_box.get_content_bounds().get_width() <= 0.0
849 && layout_box.get_content_bounds().get_height() <= 0.0;
850 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
851 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
852 } else {
853 let max_x: f32 = (layout_box.get_content_size().get_width()
854 - layout_box.get_content_bounds().get_width())
855 .max(0.0);
856 let max_y: f32 = (layout_box.get_content_size().get_height()
857 - layout_box.get_content_bounds().get_height())
858 .max(0.0);
859 Point::new(
860 offset.get_x().clamp(0.0, max_x),
861 offset.get_y().clamp(0.0, max_y),
862 )
863 };
864 if layout_box.get_scroll_offset() == clamped {
865 false
866 } else {
867 node.get_mut_layout_box().set_scroll_offset(clamped);
868 true
869 }
870 }
871 None => false,
872 };
873 if changed {
874 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
875 }
876 }
877
878 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
887 let changed: bool = match self.get_node_mut(id) {
888 Some(node) => {
889 let next: Option<(f32, f32)> = Some((scroll_y.max(0.0), content_height.max(1.0)));
890 if node.virtual_scroll_metrics() == next {
891 false
892 } else {
893 node.set_virtual_scroll(next);
894 true
895 }
896 }
897 None => false,
898 };
899 if changed {
900 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
901 }
902 }
903
904 #[must_use]
915 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
916 let node: &SceneNode = self.get_node(id)?;
917 let raw: Rect = node.get_layout_box().get_bounds();
918 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
919 self.node_scroll_and_transform(node);
920 Some(Rect::new(
921 raw.get_x() - off.get_x() + tx,
922 raw.get_y() - off.get_y() + ty,
923 raw.get_width() * sx,
924 raw.get_height() * sy,
925 ))
926 }
927
928 #[inline]
939 fn node_scroll_and_transform(&self, node: &SceneNode) -> (Point, f32, f32, f32, f32) {
940 let style: &Style = node.style_ref();
941 let tr: Transform2D = style.get_paint().get_transform();
942 let mut tx: f32 = tr.get_translate_x();
943 let mut ty: f32 = tr.get_translate_y();
944 let sx_scale: f32 = tr.get_scale_x();
945 let sy_scale: f32 = tr.get_scale_y();
946 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
947 || style.get_layout().get_position() == Position::Fixed;
948 let mut scroll_x: f32 = 0.0;
949 let mut scroll_y: f32 = 0.0;
950 let mut cursor: Option<NodeId> = node.parent_id();
951 while let Some(pid) = cursor {
952 if let Some(pnode) = self.get_node(pid) {
953 let pstyle: &Style = pnode.style_ref();
954 let ptr: Transform2D = pstyle.get_paint().get_transform();
955 tx += ptr.get_translate_x();
956 ty += ptr.get_translate_y();
957 if !start_top_layer {
958 let off: Point = pnode.get_layout_box().get_scroll_offset();
959 scroll_x += off.get_x();
960 scroll_y += off.get_y();
961 }
962 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
963 || pstyle.get_layout().get_position() == Position::Fixed;
964 if parent_top_layer {
965 break;
966 }
967 cursor = pnode.parent_id();
968 } else {
969 break;
970 }
971 }
972 (Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale)
973 }
974
975 #[must_use]
988 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
989 let node: &SceneNode = self.get_node(id)?;
990 let raw_bounds: Rect = node.get_layout_box().get_bounds();
991 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
992 return Some(Rect::default());
993 }
994 let style: &Style = node.style_ref();
995 let paint: &PaintStyle = style.paint_ref();
996 let tr: Transform2D = paint.get_transform();
997 if tr.get_rotation_rad().abs() > 0.0001
998 || tr.get_scale_x() <= 0.0
999 || tr.get_scale_y() <= 0.0
1000 {
1001 return None;
1002 }
1003 let mut tx: f32 = tr.get_translate_x();
1004 let mut ty: f32 = tr.get_translate_y();
1005 let sx: f32 = tr.get_scale_x();
1006 let sy: f32 = tr.get_scale_y();
1007 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
1008 || style.layout_ref().get_position() == Position::Fixed;
1009 let mut scroll_x: f32 = 0.0;
1010 let mut scroll_y: f32 = 0.0;
1011 let mut cursor: Option<NodeId> = node.parent_id();
1012 while let Some(pid) = cursor {
1013 let Some(pnode) = self.get_node(pid) else {
1014 break;
1015 };
1016 let pstyle: &Style = pnode.style_ref();
1017 let ptr: Transform2D = pstyle.paint_ref().get_transform();
1018 if ptr.get_rotation_rad().abs() > 0.0001
1019 || (ptr.get_scale_x() - 1.0).abs() > 0.001
1020 || (ptr.get_scale_y() - 1.0).abs() > 0.001
1021 {
1022 return None;
1023 }
1024 tx += ptr.get_translate_x();
1025 ty += ptr.get_translate_y();
1026 if !start_top_layer {
1027 let off: Point = pnode.get_layout_box().get_scroll_offset();
1028 scroll_x += off.get_x();
1029 scroll_y += off.get_y();
1030 }
1031 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
1032 || pstyle.layout_ref().get_position() == Position::Fixed;
1033 if parent_top_layer {
1034 break;
1035 }
1036 cursor = pnode.parent_id();
1037 }
1038 let border_w: f32 = paint.get_border().get_width();
1039 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
1040 12.0
1041 } else {
1042 0.0
1043 };
1044 let mut margin: f32 = 10.0_f32.max(border_w + 6.0).max(focus_pad);
1045 if let Some(shadow) = paint.box_shadow() {
1046 let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
1047 let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
1048 let spread: f32 = shadow.get_spread_radius().max(0.0);
1049 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
1050 margin = margin.max(blur_pad + spread + off_max + 4.0);
1051 }
1052 let backdrop_blur: f32 = self.backdrop_blur_radius(id);
1053 if backdrop_blur > 0.0 {
1054 let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
1055 let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
1056 margin = margin.max(blur_halo);
1057 }
1058 let base_x: f32 = raw_bounds.get_x() - scroll_x;
1059 let base_y: f32 = raw_bounds.get_y() - scroll_y;
1060 let base_rect: Rect = Rect::new(
1061 base_x - margin,
1062 base_y - margin,
1063 raw_bounds.get_width() + margin * 2.0,
1064 raw_bounds.get_height() + margin * 2.0,
1065 );
1066 let shifted_x: bool = tx != 0.0 || sx != 1.0;
1067 let shifted_y: bool = ty != 0.0 || sy != 1.0;
1068 if shifted_x || shifted_y {
1069 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
1070 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
1071 let shifted_rect: Rect = Rect::new(
1072 base_x + tx - margin - scale_pad_x,
1073 base_y + ty - margin - scale_pad_y,
1074 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
1075 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
1076 );
1077 Some(base_rect.union(shifted_rect))
1078 } else {
1079 Some(base_rect)
1080 }
1081 }
1082
1083 #[must_use]
1094 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
1095 let x0: f32 = (logical.get_x() * scale).floor();
1096 let y0: f32 = (logical.get_y() * scale).floor();
1097 let x1: f32 = (logical.right() * scale).ceil();
1098 let y1: f32 = (logical.bottom() * scale).ceil();
1099 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
1100 }
1101
1102 fn record_node_logical_damage(&mut self, id: NodeId) {
1109 if self.get_full_damage_pending() {
1110 return;
1111 }
1112 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
1113 match rect_opt {
1114 Some(rect) => {
1115 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
1116 return;
1117 }
1118 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1119 self.set_full_damage_pending(true);
1120 self.set_full_damage_overflow(true);
1121 self.get_mut_extra_logical_damage().clear();
1122 } else {
1123 self.get_mut_extra_logical_damage().push(rect);
1124 }
1125 }
1126 None => {
1127 self.set_full_damage_pending(true);
1128 }
1129 }
1130 }
1131
1132 fn record_subtree_logical_damage(&mut self, root: NodeId) {
1139 if self.get_full_damage_pending() {
1140 return;
1141 }
1142 let mut stack: Vec<NodeId> = vec![root];
1143 let mut visited: usize = 0;
1144 while let Some(current) = stack.pop() {
1145 let Some(node) = self.get_node(current) else {
1146 continue;
1147 };
1148 visited += 1;
1149 if visited > DIRTY_PAINT_FULL_THRESHOLD {
1150 self.set_full_damage_pending(true);
1151 self.set_full_damage_overflow(true);
1152 self.get_mut_extra_logical_damage().clear();
1153 return;
1154 }
1155 let children: Vec<NodeId> = node.get_children().clone();
1156 let raw_bounds: Rect = node.get_layout_box().get_bounds();
1157 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
1158 self.record_node_logical_damage(current);
1159 if self.get_full_damage_pending() {
1160 return;
1161 }
1162 }
1163 for child in children.into_iter() {
1164 stack.push(child);
1165 }
1166 }
1167 }
1168
1169 pub fn start_transition(&mut self, mut transition: NodeTransition) {
1176 let target: NodeId = transition.get_node();
1177 let had_active: bool = self
1178 .get_transitions()
1179 .iter()
1180 .any(|tr: &NodeTransition| tr.get_node() == target);
1181 self.get_mut_transitions()
1182 .retain(|tr: &NodeTransition| tr.get_node() != target);
1183 if had_active && let Some(node) = self.get_node(target) {
1184 let paint: PaintStyle = node.get_style().get_paint();
1185 let tr: Transform2D = paint.get_transform();
1186 let cur_op: f32 = paint.get_opacity();
1187 let cur_tx: f32 = tr.get_translate_x();
1188 let cur_ty: f32 = tr.get_translate_y();
1189 let cur_sc: f32 = tr.get_scale_x();
1190 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
1191 .hypot(transition.get_to_ty() - transition.get_from_ty())
1192 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
1193 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
1194 .hypot(transition.get_to_ty() - cur_ty)
1195 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
1196 if full_dist > 0.01 {
1197 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
1198 transition.set_duration((transition.get_duration() * ratio).max(0.05));
1199 }
1200 transition.set_from_opacity(cur_op);
1201 transition.set_from_tx(cur_tx);
1202 transition.set_from_ty(cur_ty);
1203 transition.set_from_scale(cur_sc);
1204 }
1205 self.record_node_logical_damage(target);
1206 let (opacity, transform): (f32, Transform2D) = transition.sample();
1207 let mut unhidden: bool = false;
1208 if let Some(node) = self.get_node_mut(target) {
1209 let style: &mut Style = node.get_mut_style();
1210 if !transition.get_hide_on_complete()
1211 && style.layout_ref().get_display() == Display::None
1212 {
1213 style.get_mut_layout().set_display(Display::Flex);
1214 unhidden = true;
1215 }
1216 style.get_mut_paint().set_opacity(opacity);
1217 style.get_mut_paint().set_transform(transform);
1218 }
1219 if unhidden {
1220 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1221 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1222 } else {
1223 self.mark_dirty(target, DIRTY_COMPOSITE);
1224 }
1225 self.get_mut_transitions().push(transition);
1226 }
1227
1228 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
1239 let len: usize = self.get_transitions().len();
1240 if len == 0 {
1241 return false;
1242 }
1243 let step: f32 = dt_secs.clamp(0.001, 0.05);
1244 let mut any_updated: bool = false;
1245 let mut write_idx: usize = 0;
1246 for read_idx in 0..len {
1247 let target: NodeId = self.get_transitions()[read_idx].get_node();
1248 if self.get_node(target).is_none() {
1249 continue;
1250 }
1251 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
1252 let tr: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
1253 let total_span: f32 = tr.get_delay() + tr.get_duration();
1254 let prev_elapsed: f32 = tr.get_elapsed();
1255 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
1256 tr.set_elapsed(next_elapsed);
1257 let is_done: bool = tr.is_complete();
1258 let in_hold: bool =
1259 prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !is_done;
1260 if in_hold {
1261 (is_done, None, false)
1262 } else {
1263 let sampled: (f32, Transform2D) = tr.sample();
1264 let should_hide: bool = is_done && tr.get_hide_on_complete();
1265 (is_done, Some(sampled), should_hide)
1266 }
1267 };
1268 if let Some((opacity, transform)) = sample_opt {
1269 self.record_node_logical_damage(target);
1270 if let Some(node) = self.get_node_mut(target) {
1271 let style: &mut Style = node.get_mut_style();
1272 style.get_mut_paint().set_opacity(opacity);
1273 style.get_mut_paint().set_transform(transform);
1274 if hide {
1275 style.get_mut_layout().set_display(Display::None);
1276 }
1277 }
1278 if hide {
1279 self.clear_subtree_hover(target);
1280 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1281 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1282 } else {
1283 self.mark_dirty(target, DIRTY_COMPOSITE);
1284 }
1285 any_updated = true;
1286 }
1287 if !done {
1288 if write_idx != read_idx {
1289 self.get_mut_transitions().swap(write_idx, read_idx);
1290 }
1291 write_idx += 1;
1292 }
1293 }
1294 self.get_mut_transitions().truncate(write_idx);
1295 any_updated
1296 }
1297
1298 fn clear_subtree_hover(&mut self, root: NodeId) {
1305 let mut stack: Vec<NodeId> = vec![root];
1306 while let Some(id) = stack.pop() {
1307 if self.get_focus().hovered_node() == Some(id) {
1308 self.get_mut_focus().set_hovered(None);
1309 }
1310 if self.get_focus().pressed_node() == Some(id) {
1311 self.get_mut_focus().set_pressed(None);
1312 }
1313 if self.get_focus().focused_node() == Some(id) {
1314 self.get_mut_focus().set_focused(None);
1315 }
1316 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(id) {
1317 Some(node) => {
1318 node.get_mut_interaction().set_hovered(false);
1319 node.get_mut_interaction().set_pressed(false);
1320 node.get_mut_interaction().set_focused(false);
1321 if node.get_children().is_empty() {
1322 None
1323 } else {
1324 Some(node.get_children().clone())
1325 }
1326 }
1327 None => continue,
1328 };
1329 if let Some(children) = children_opt {
1330 stack.extend(children);
1331 }
1332 }
1333 }
1334
1335 #[must_use]
1345 pub fn has_active_transitions(&self) -> bool {
1346 !self.get_transitions().is_empty()
1347 }
1348
1349 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
1357 if let Some(node) = self.get_node_mut(id) {
1358 node.add_lifecycle(hook);
1359 }
1360 }
1361
1362 #[must_use]
1373 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1374 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1375 let mut stack: Vec<NodeId> = vec![root];
1376 while let Some(current) = stack.pop() {
1377 if let Some(node) = self.get_node(current) {
1378 for hook in node.lifecycle_observers().into_iter() {
1379 out.push((current, hook));
1380 }
1381 for child in node.get_children().iter().rev().copied() {
1382 stack.push(child);
1383 }
1384 }
1385 }
1386 out
1387 }
1388
1389 #[must_use]
1399 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1400 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1401 let mut stack: Vec<NodeId> = vec![self.get_root()];
1402 while let Some(current) = stack.pop() {
1403 if let Some(node) = self.get_node(current) {
1404 if node.style_ref().layout_ref().get_display() == Display::None {
1405 continue;
1406 }
1407 for hook in node.lifecycle_observers().into_iter() {
1408 out.push((current, hook));
1409 }
1410 for child in node.get_children().iter().rev().copied() {
1411 stack.push(child);
1412 }
1413 }
1414 }
1415 out
1416 }
1417
1418 #[must_use]
1429 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
1430 let mut out: Vec<ScopeId> = Vec::new();
1431 let mut stack: Vec<NodeId> = vec![root];
1432 while let Some(current) = stack.pop() {
1433 if let Some(node) = self.get_node(current) {
1434 if let Some(scope) = node.owned_scope() {
1435 out.push(scope.id());
1436 }
1437 for child in node.get_children().iter().rev().copied() {
1438 stack.push(child);
1439 }
1440 }
1441 }
1442 out
1443 }
1444
1445 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
1452 if self.get_transitions().is_empty() {
1453 return;
1454 }
1455 let mut ids: HashSet<NodeId> = HashSet::new();
1456 let mut stack: Vec<NodeId> = vec![root];
1457 while let Some(current) = stack.pop() {
1458 if ids.insert(current)
1459 && let Some(node) = self.get_node(current)
1460 {
1461 for child in node.get_children().iter().copied() {
1462 stack.push(child);
1463 }
1464 }
1465 }
1466 self.get_mut_transitions()
1467 .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
1468 }
1469
1470 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
1478 if let Some(node) = self.get_node_mut(id) {
1479 if let Some(existing) = node.owned_scope() {
1480 existing.enter(|| {
1481 on_cleanup(move || {
1482 scope.dispose();
1483 });
1484 });
1485 } else {
1486 node.set_scope(Some(scope));
1487 }
1488 }
1489 }
1490
1491 pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
1499 let check_portal: bool = (mask & DIRTY_LAYOUT) != 0;
1500 let (prev_bits, mut parent_opt, portal_state): (u16, Option<NodeId>, Option<bool>) =
1501 match self.get_node_mut(id) {
1502 Some(node) => {
1503 let prev: u16 = node.get_dirty().get_bits();
1504 node.get_mut_dirty().insert(mask);
1505 let portal_opt: Option<bool> = if check_portal {
1506 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
1507 || node.style_ref().get_layout().get_position() == Position::Fixed;
1508 Some(is_portal)
1509 } else {
1510 None
1511 };
1512 (prev, node.parent_id(), portal_opt)
1513 }
1514 None => return,
1515 };
1516 if let Some(is_portal) = portal_state
1517 && (is_portal || self.has_portal_nodes())
1518 {
1519 self.sync_portal_registration(id, is_portal);
1520 }
1521 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
1522 self.set_layout_damage_pending(true);
1523 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
1524 }
1525 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
1526 if !self.get_full_damage_pending()
1527 && (mask & visual_mask) != 0
1528 && (prev_bits & visual_mask) == 0
1529 {
1530 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1531 self.set_full_damage_pending(true);
1532 self.set_full_damage_overflow(true);
1533 self.get_mut_dirty_paint_nodes().clear();
1534 } else {
1535 self.get_mut_dirty_paint_nodes().push(id);
1536 }
1537 }
1538 let mut ancestor_mask: u16 = DIRTY_NONE;
1539 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
1540 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
1541 }
1542 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
1543 ancestor_mask |= DIRTY_SUBTREE_PAINT;
1544 }
1545 if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
1546 ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
1547 }
1548 while let Some(ancestor_id) = parent_opt {
1549 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1550 let already: bool =
1551 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
1552 ancestor.get_mut_dirty().insert(ancestor_mask);
1553 if already {
1554 break;
1555 }
1556 parent_opt = ancestor.parent_id();
1557 } else {
1558 break;
1559 }
1560 }
1561 let next_rev: u64 = self.get_revision().wrapping_add(1);
1562 self.set_revision(next_rev);
1563 }
1564
1565 #[must_use]
1576 pub fn is_node_visible(&self, id: NodeId) -> bool {
1577 let root: NodeId = self.get_root();
1578 let mut cursor: Option<NodeId> = Some(id);
1579 while let Some(cur) = cursor {
1580 let Some(node) = self.get_node(cur) else {
1581 return false;
1582 };
1583 let style: &Style = node.style_ref();
1584 if style.get_layout().get_display() == Display::None
1585 || style.get_paint().get_opacity() <= 0.001
1586 {
1587 return false;
1588 }
1589 if cur == root {
1590 return true;
1591 }
1592 cursor = node.parent_id();
1593 }
1594 false
1595 }
1596
1597 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
1608 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
1609 damage
1610 }
1611
1612 pub(crate) fn collect_surgical_paint_damage(
1624 &mut self,
1625 scale: f32,
1626 allow_partial_layout: bool,
1627 ) -> (DamageRegion, bool) {
1628 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
1629 let layout_pending: bool = self.get_layout_damage_pending();
1630 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
1631 let no_extra: bool = self.get_extra_logical_damage().is_empty();
1632 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
1633 self.set_created_since_damage(0);
1634 self.set_last_collect_composite_only(false);
1635 return (DamageRegion::default(), false);
1636 }
1637 let mut full: bool =
1638 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
1639 let mut saw_paint_or_layout: bool = layout_pending;
1640 let mut saw_composite_or_scroll: bool = false;
1641 let mut region: DamageRegion = DamageRegion::default();
1642 if !full {
1643 let extra_len: usize = self.get_extra_logical_damage().len();
1644 for i in 0..extra_len {
1645 let logical_rect: Rect = self.get_extra_logical_damage()[i];
1646 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
1647 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1648 }
1649 }
1650 let dirty_len: usize = self.get_dirty_paint_nodes().len();
1651 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
1652 for i in 0..dirty_len {
1653 let nid: NodeId = self.get_dirty_paint_nodes()[i];
1654 let Some(node) = self.get_node(nid) else {
1655 continue;
1656 };
1657 let bits: u16 = node.get_dirty().get_bits();
1658 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
1659 if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
1660 saw_paint_or_layout = true;
1661 }
1662 if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
1663 saw_composite_or_scroll = true;
1664 }
1665 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
1666 full = true;
1667 break;
1668 }
1669 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
1670 full = true;
1671 break;
1672 }
1673 if (bits & visual_mask) == 0 {
1674 continue;
1675 }
1676 let raw_bounds: Rect = node.get_layout_box().get_bounds();
1677 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
1678 match self.node_conservative_logical_rect(nid) {
1679 Some(logical_rect) => {
1680 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1681 }
1682 None => {
1683 full = true;
1684 break;
1685 }
1686 }
1687 } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
1688 && !has_layout_bits
1689 && node.style_ref().layout_ref().get_display() != Display::None
1690 {
1691 full = true;
1692 break;
1693 }
1694 }
1695 }
1696 self.set_last_collect_composite_only(
1697 !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
1698 );
1699 self.set_layout_damage_pending(false);
1700 self.set_created_since_damage(0);
1701 self.get_mut_extra_logical_damage().clear();
1702 if !full {
1703 let dirty_len: usize = self.get_dirty_paint_nodes().len();
1704 let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
1705 for i in 0..dirty_len {
1706 let nid: NodeId = self.get_dirty_paint_nodes()[i];
1707 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
1708 Some(node) => {
1709 node.get_mut_dirty().remove(clear_mask);
1710 node.parent_id()
1711 }
1712 None => None,
1713 };
1714 while let Some(ancestor_id) = parent_opt {
1715 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1716 if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
1717 break;
1718 }
1719 ancestor.get_mut_dirty().remove(ancestor_clear);
1720 parent_opt = ancestor.parent_id();
1721 } else {
1722 break;
1723 }
1724 }
1725 }
1726 self.get_mut_dirty_paint_nodes().clear();
1727 return (region, layout_pending);
1728 }
1729 self.set_full_damage_pending(false);
1730 self.get_mut_dirty_paint_nodes().clear();
1731 for node in self.get_mut_nodes().iter_mut() {
1732 if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
1733 node.get_mut_dirty().remove(clear_mask);
1734 }
1735 }
1736 (DamageRegion::full(), layout_pending)
1737 }
1738
1739 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
1749 let was_overflow: bool = self.get_full_damage_overflow();
1750 self.set_full_damage_overflow(false);
1751 was_overflow
1752 }
1753
1754 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
1765 if id == self.get_root() {
1766 return (Vec::new(), Vec::new());
1767 }
1768 self.record_subtree_logical_damage(id);
1769 self.cancel_subtree_transitions(id);
1770 let mut stack: Vec<NodeId> = vec![id];
1771 let mut scopes: Vec<Scope> = Vec::new();
1772 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1773 while let Some(current) = stack.pop() {
1774 let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
1775 Some(node) => {
1776 node.set_alive(false);
1777 if node.has_extras() {
1778 if let Some(scope) = node.owned_scope() {
1779 scopes.push(scope);
1780 }
1781 for hook in node.take_lifecycles().into_iter() {
1782 observers.push((current, hook));
1783 }
1784 node.clear_extras();
1785 }
1786 node.set_parent(None);
1787 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
1788 node.set_generation(next_gen);
1789 Some(take(node.get_mut_children()))
1790 }
1791 None => None,
1792 };
1793 let Some(children) = children_opt else {
1794 continue;
1795 };
1796 let next_live: usize = self.get_live_count().saturating_sub(1);
1797 self.set_live_count(next_live);
1798 if !self.portal_nodes().is_empty() {
1799 self.sync_portal_registration(current, false);
1800 }
1801 if !self.get_backdrop_blur_nodes().is_empty() {
1802 self.get_mut_backdrop_blur_nodes()
1803 .retain(|entry: &(NodeId, f32)| entry.0 != current);
1804 }
1805 if self.get_focus().focused_node() == Some(current) {
1806 self.get_mut_focus().set_focused(None);
1807 }
1808 if self.get_focus().hovered_node() == Some(current) {
1809 self.get_mut_focus().set_hovered(None);
1810 }
1811 if self.get_focus().pressed_node() == Some(current) {
1812 self.get_mut_focus().set_pressed(None);
1813 }
1814 if self
1815 .text_selection()
1816 .map(|sel: SelectionState| sel.get_node_id())
1817 == Some(current)
1818 {
1819 self.set_text_selection(None);
1820 }
1821 self.get_mut_free_list().push(current.get_index());
1822 for child in children.into_iter() {
1823 stack.push(child);
1824 }
1825 }
1826 (scopes, observers)
1827 }
1828
1829 pub fn dispose_subtree(&mut self, id: NodeId) {
1836 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
1837 finalize_disposed_subtree(scopes, observers);
1838 }
1839
1840 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
1851 let prev: Option<NodeId> = self.get_focus().focused_node();
1852 if prev == target {
1853 return Vec::new();
1854 }
1855 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
1856 if let Some(old_id) = prev {
1857 if let Some(old_node) = self.get_node_mut(old_id) {
1858 old_node.get_mut_interaction().set_focused(false);
1859 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
1860 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
1861 }
1862 }
1863 self.mark_dirty(old_id, DIRTY_PAINT);
1864 }
1865 self.get_mut_focus().set_focused(target);
1866 if let Some(new_id) = target {
1867 if let Some(new_node) = self.get_node_mut(new_id) {
1868 new_node.get_mut_interaction().set_focused(true);
1869 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
1870 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
1871 }
1872 }
1873 self.mark_dirty(new_id, DIRTY_PAINT);
1874 }
1875 callbacks
1876 }
1877
1878 #[must_use]
1889 pub fn is_node_selectable(&self, id: NodeId) -> bool {
1890 let mut cursor: Option<NodeId> = Some(id);
1891 while let Some(cur) = cursor {
1892 let Some(node) = self.get_node(cur) else {
1893 return false;
1894 };
1895 let text_style: &TextStyle = node.style_ref().text_ref();
1896 if text_style.get_selectable() {
1897 return true;
1898 }
1899 if text_style.get_selectable_explicit() {
1900 return false;
1901 }
1902 cursor = node.parent_id();
1903 }
1904 false
1905 }
1906
1907 #[must_use]
1918 pub fn effective_selection_color(&self, id: NodeId) -> Color {
1919 let mut cursor: Option<NodeId> = Some(id);
1920 while let Some(cur) = cursor {
1921 let Some(node) = self.get_node(cur) else {
1922 break;
1923 };
1924 if let Some(color) = node.style_ref().text_ref().selection_color() {
1925 return color;
1926 }
1927 cursor = node.parent_id();
1928 }
1929 DEFAULT_TEXT_SELECTION_COLOR
1930 }
1931
1932 #[must_use]
1942 pub fn text_selection(&self) -> Option<SelectionState> {
1943 let Self { text_selection, .. } = self;
1944 *text_selection
1945 }
1946
1947 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
1954 let prev: Option<SelectionState> = self.text_selection();
1955 if prev == selection {
1956 return;
1957 }
1958 let Self { text_selection, .. } = self;
1959 *text_selection = selection;
1960 if let Some(old_sel) = prev {
1961 self.mark_dirty(old_sel.get_node_id(), DIRTY_PAINT);
1962 }
1963 if let Some(new_sel) = selection {
1964 self.mark_dirty(new_sel.get_node_id(), DIRTY_PAINT);
1965 }
1966 }
1967
1968 pub fn clear_text_selection(&mut self) {
1974 self.set_text_selection(None);
1975 }
1976
1977 #[must_use]
1987 pub fn get_selected_text(&self) -> Option<String> {
1988 let sel: SelectionState = self.text_selection()?;
1989 if sel.is_empty() {
1990 return None;
1991 }
1992 let node: &SceneNode = self.get_node(sel.get_node_id())?;
1993 let NodeKind::Text(content) = node.get_kind() else {
1994 return None;
1995 };
1996 let extracted: &str = sel.extract_from(content.as_str());
1997 if extracted.is_empty() {
1998 None
1999 } else {
2000 Some(extracted.to_string())
2001 }
2002 }
2003
2004 pub fn select_all_text(&mut self, id: NodeId) -> bool {
2015 if !self.is_node_selectable(id) {
2016 return false;
2017 }
2018 let char_len: Option<usize> = self.get_node(id).and_then(|node: &SceneNode| {
2019 if let NodeKind::Text(content) = node.get_kind() {
2020 Some(content.chars().count())
2021 } else {
2022 None
2023 }
2024 });
2025 let Some(len) = char_len else {
2026 return false;
2027 };
2028 if len == 0 {
2029 return false;
2030 }
2031 self.set_text_selection(Some(SelectionState::new(id, 0, len)));
2032 true
2033 }
2034}
2035
2036impl SceneHandle {
2038 #[must_use]
2044 pub fn new_tree() -> Self {
2045 Self {
2046 inner: Rc::new(RefCell::new(SceneTree::default())),
2047 }
2048 }
2049
2050 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
2059 self.with_write(
2060 |tree: &mut SceneTree| {
2061 tree.set_virtual_scroll(id, scroll_y, content_height);
2062 },
2063 (),
2064 );
2065 }
2066
2067 #[must_use]
2078 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
2079 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
2080 }
2081
2082 pub fn start_transition(&self, transition: NodeTransition) {
2089 self.with_write(
2090 |tree: &mut SceneTree| {
2091 tree.start_transition(transition);
2092 },
2093 (),
2094 );
2095 }
2096
2097 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
2105 self.with_write(
2106 |tree: &mut SceneTree| {
2107 tree.mark_dirty(id, mask);
2108 },
2109 (),
2110 );
2111 }
2112
2113 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
2121 let (scopes, observers): DisposedSubtreePayload = self.with_write(
2122 |tree: &mut SceneTree| {
2123 let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
2124 Some(node) => take(node.get_mut_children()),
2125 None => return (Vec::new(), Vec::new()),
2126 };
2127 let mut all_scopes: Vec<Scope> = Vec::new();
2128 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
2129 if new_children.is_empty() {
2130 for old_child in old_children.into_iter() {
2131 let (sc, ob): DisposedSubtreePayload =
2132 tree.dispose_subtree_collect(old_child);
2133 all_scopes.extend(sc);
2134 all_obs.extend(ob);
2135 }
2136 } else if old_children.len() > 16 && new_children.len() > 16 {
2137 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
2138 for old_child in old_children.into_iter() {
2139 if !keep_set.contains(&old_child) {
2140 let (sc, ob): DisposedSubtreePayload =
2141 tree.dispose_subtree_collect(old_child);
2142 all_scopes.extend(sc);
2143 all_obs.extend(ob);
2144 }
2145 }
2146 } else {
2147 for old_child in old_children.into_iter() {
2148 if !new_children.contains(&old_child) {
2149 let (sc, ob): DisposedSubtreePayload =
2150 tree.dispose_subtree_collect(old_child);
2151 all_scopes.extend(sc);
2152 all_obs.extend(ob);
2153 }
2154 }
2155 }
2156 for child in new_children.iter().copied() {
2157 if let Some(child_node) = tree.get_node_mut(child) {
2158 child_node.set_parent(Some(parent));
2159 }
2160 }
2161 if let Some(parent_node) = tree.get_node_mut(parent) {
2162 parent_node.set_children(new_children);
2163 }
2164 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
2165 (all_scopes, all_obs)
2166 },
2167 (Vec::new(), Vec::new()),
2168 );
2169 finalize_disposed_subtree(scopes, observers);
2170 }
2171
2172 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
2180 let (scopes, observers): DisposedSubtreePayload = self.with_write(
2181 |tree: &mut SceneTree| {
2182 if let Some(pnode) = tree.get_node_mut(parent) {
2183 pnode.get_mut_children().retain(|id: &NodeId| *id != child);
2184 }
2185 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
2186 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
2187 out
2188 },
2189 (Vec::new(), Vec::new()),
2190 );
2191 finalize_disposed_subtree(scopes, observers);
2192 }
2193
2194 pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
2206 where
2207 F: FnOnce(&mut Style),
2208 {
2209 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
2210 }
2211
2212 pub fn freeze_subtree(&self, root: NodeId) {
2219 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2220 |tree: &mut SceneTree| {
2221 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
2222 tree.cancel_subtree_transitions(root);
2223 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
2224 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
2225 if layout.get_display() == Display::None {
2226 false
2227 } else {
2228 layout.set_display(Display::None);
2229 true
2230 }
2231 } else {
2232 false
2233 };
2234 if changed {
2235 tree.clear_subtree_hover(root);
2236 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2237 }
2238 obs
2239 },
2240 Vec::new(),
2241 );
2242 dispatch_lifecycle_freeze(&observers);
2243 }
2244
2245 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
2253 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2254 |tree: &mut SceneTree| {
2255 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
2256 tree.cancel_subtree_transitions(root);
2257 let mut demoted_fixed: bool = false;
2258 if let Some(node) = tree.get_node_mut(root) {
2259 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
2260 let st: &mut Style = node.get_mut_style();
2261 demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
2262 st.get_mut_layout()
2263 .set_position(Position::Absolute)
2264 .set_top(Some(0.0))
2265 .set_right(Some(0.0))
2266 .set_bottom(None)
2267 .set_left(Some(0.0))
2268 .set_z_index(0);
2269 st.get_mut_paint().set_pointer_events(PointerEvents::None);
2270 }
2271 tree.clear_subtree_hover(root);
2272 if demoted_fixed {
2273 tree.sync_portal_registration(root, false);
2274 }
2275 tree.start_transition(exit_transition.with_hide_on_complete(true));
2276 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2277 obs
2278 },
2279 Vec::new(),
2280 );
2281 dispatch_lifecycle_freeze(&observers);
2282 }
2283
2284 pub fn resume_subtree(&self, root: NodeId) {
2291 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2292 |tree: &mut SceneTree| {
2293 let mut unhidden: bool = false;
2294 if let Some(node) = tree.get_node_mut(root) {
2295 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
2296 if layout.get_display() == Display::None {
2297 layout.set_display(Display::Flex);
2298 unhidden = true;
2299 }
2300 }
2301 if unhidden {
2302 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2303 } else {
2304 tree.mark_dirty(root, DIRTY_PAINT);
2305 }
2306 tree.collect_subtree_lifecycles(root)
2307 },
2308 Vec::new(),
2309 );
2310 dispatch_lifecycle_resume(&observers);
2311 }
2312
2313 pub fn activate_subtree(&self, root: NodeId) {
2320 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2321 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2322 Vec::new(),
2323 );
2324 dispatch_lifecycle_activate(&observers);
2325 }
2326
2327 pub fn update_subtree(&self, root: NodeId) {
2334 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2335 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2336 Vec::new(),
2337 );
2338 dispatch_lifecycle_update(&observers);
2339 }
2340
2341 pub fn emit_subtree_appear(&self, root: NodeId) {
2348 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2349 |tree: &SceneTree| {
2350 (
2351 tree.collect_subtree_lifecycles(root),
2352 tree.collect_subtree_scope_ids(root),
2353 )
2354 },
2355 (Vec::new(), Vec::new()),
2356 );
2357 let ev: SystemEvent = SystemEvent::Appear;
2358 dispatch_lifecycle_system_event(&observers, &ev);
2359 dispatch_system_event_to_scopes(&scopes, &ev);
2360 }
2361
2362 pub fn emit_subtree_disappear(&self, root: NodeId) {
2369 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2370 |tree: &SceneTree| {
2371 (
2372 tree.collect_subtree_lifecycles(root),
2373 tree.collect_subtree_scope_ids(root),
2374 )
2375 },
2376 (Vec::new(), Vec::new()),
2377 );
2378 let ev: SystemEvent = SystemEvent::Disappear;
2379 dispatch_lifecycle_system_event(&observers, &ev);
2380 dispatch_system_event_to_scopes(&scopes, &ev);
2381 }
2382
2383 #[must_use]
2393 pub fn has_active_transitions(&self) -> bool {
2394 self.with_read(SceneTree::has_active_transitions, false)
2395 }
2396
2397 #[must_use]
2407 pub fn get_selected_text(&self) -> Option<String> {
2408 self.with_read(SceneTree::get_selected_text, None)
2409 }
2410
2411 pub fn clear_text_selection(&self) {
2417 self.with_write(SceneTree::clear_text_selection, ());
2418 }
2419
2420 pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
2432 where
2433 F: FnOnce(&SceneTree) -> R,
2434 {
2435 let Self { inner } = self;
2436 match inner.try_borrow() {
2437 Ok(guard) => operation(&guard),
2438 Err(_) => fallback,
2439 }
2440 }
2441
2442 pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
2454 where
2455 F: FnOnce(&mut SceneTree) -> R,
2456 {
2457 let Self { inner } = self;
2458 match inner.try_borrow_mut() {
2459 Ok(mut guard) => operation(&mut guard),
2460 Err(_) => fallback,
2461 }
2462 }
2463
2464 pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2476 where
2477 F: FnMut() -> String + 'static,
2478 {
2479 let handle: Self = self.clone();
2480 Effect::new(move || {
2481 let value: String = producer();
2482 handle.with_write(
2483 |tree: &mut SceneTree| {
2484 tree.set_text(node_id, value);
2485 },
2486 (),
2487 );
2488 })
2489 }
2490
2491 pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2503 where
2504 F: FnMut() -> Style + 'static,
2505 {
2506 let handle: Self = self.clone();
2507 Effect::new(move || {
2508 let style: Style = producer();
2509 handle.with_write(
2510 |tree: &mut SceneTree| {
2511 tree.set_style(node_id, style);
2512 },
2513 (),
2514 );
2515 })
2516 }
2517}
2518
2519impl Context {
2521 #[must_use]
2532 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
2533 Self {
2534 scene,
2535 breakpoint: Signal::new(Breakpoint::Expanded),
2536 viewport_size: Signal::new(Size::new(1200.0, 800.0)),
2537 theme_mode: Signal::new(ThemeMode::Light),
2538 platform,
2539 safe_area: Signal::new(SafeAreaInsets::default()),
2540 gesture: Signal::new(None),
2541 swipe_drag_offset: Signal::new(0.0),
2542 system_back: Signal::new(0),
2543 dynamic_hub: DynamicUpdateHub::new(),
2544 fps_limit: Signal::new(None),
2545 live_fps: Signal::new(60.0),
2546 present_fps: Signal::new(0.0),
2547 is_idle: Signal::new(true),
2548 display_refresh_rate: Signal::new(60.0),
2549 active_touches: Signal::new(Vec::new()),
2550 exit_requested: Signal::new(false),
2551 app_state: Signal::new(AppState::Active),
2552 network_status: Signal::new(NetworkStatus::Online),
2553 keyboard_visible: Signal::new(false),
2554 keyboard_height: Signal::new(0.0),
2555 orientation: Signal::new(ScreenOrientation::Landscape),
2556 low_power_mode: Signal::new(false),
2557 locale: Signal::new(DEFAULT_SYSTEM_LOCALE.to_string()),
2558 window_focused: Signal::new(true),
2559 immersive_fullscreen: Signal::new(false),
2560 fullscreen_depth: Rc::new(Cell::new(0)),
2561 clock_ms: Rc::new(Cell::new(0)),
2562 }
2563 }
2564
2565 #[must_use]
2575 pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
2576 self.get_safe_area()
2577 }
2578
2579 #[must_use]
2589 pub fn safe_area(&self) -> SafeAreaInsets {
2590 self.get_safe_area().get()
2591 }
2592
2593 #[must_use]
2603 pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
2604 self.get_immersive_fullscreen()
2605 }
2606
2607 #[must_use]
2617 pub fn is_immersive_fullscreen(&self) -> bool {
2618 self.get_immersive_fullscreen().get()
2619 }
2620
2621 pub fn set_immersive_fullscreen(&self, enabled: bool) {
2628 let Self {
2629 fullscreen_depth, ..
2630 } = self;
2631 if enabled {
2632 if fullscreen_depth.get() == 0 {
2633 fullscreen_depth.set(1);
2634 }
2635 let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
2636 } else {
2637 fullscreen_depth.set(0);
2638 let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
2639 }
2640 }
2641
2642 pub fn enter_immersive_fullscreen(&self) {
2648 let Self {
2649 fullscreen_depth, ..
2650 } = self;
2651 let next: u32 = fullscreen_depth.get().saturating_add(1);
2652 fullscreen_depth.set(next);
2653 let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
2654 }
2655
2656 pub fn exit_immersive_fullscreen(&self) {
2662 let Self {
2663 fullscreen_depth, ..
2664 } = self;
2665 let next: u32 = fullscreen_depth.get().saturating_sub(1);
2666 fullscreen_depth.set(next);
2667 if next == 0 {
2668 let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
2669 }
2670 }
2671
2672 #[must_use]
2682 pub fn app_state_signal(&self) -> Signal<AppState> {
2683 self.get_app_state()
2684 }
2685
2686 pub fn emit_page_appear(&self) {
2692 let ev: SystemEvent = SystemEvent::Appear;
2693 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2694 .get_scene()
2695 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2696 dispatch_lifecycle_system_event(&observers, &ev);
2697 dispatch_system_event_listeners(&ev);
2698 }
2699
2700 pub fn emit_page_disappear(&self) {
2706 let ev: SystemEvent = SystemEvent::Disappear;
2707 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2708 .get_scene()
2709 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2710 dispatch_lifecycle_system_event(&observers, &ev);
2711 dispatch_system_event_listeners(&ev);
2712 }
2713
2714 pub fn emit_subtree_appear(&self, root: NodeId) {
2721 self.get_scene().emit_subtree_appear(root);
2722 }
2723
2724 pub fn emit_subtree_disappear(&self, root: NodeId) {
2731 self.get_scene().emit_subtree_disappear(root);
2732 }
2733
2734 #[must_use]
2744 pub fn elapsed_ms(&self) -> u64 {
2745 let Self { clock_ms, .. } = self;
2746 clock_ms.get()
2747 }
2748
2749 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
2756 let Self { clock_ms, .. } = self;
2757 clock_ms.set(clock_ms.get().saturating_add(delta_ms));
2758 }
2759
2760 pub fn request_exit(&self) {
2766 let _: bool = self.get_exit_requested().set_if_changed(true);
2767 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
2768 }
2769
2770 pub fn copy_to_clipboard(&self, text: &str) -> bool {
2781 write_system_clipboard(text)
2782 }
2783
2784 pub fn view(&mut self, style: Style) -> NodeId {
2795 self.get_scene().with_write(
2796 |tree: &mut SceneTree| tree.create_view(style),
2797 NodeId::default(),
2798 )
2799 }
2800
2801 pub fn text(&mut self, content: String, style: Style) -> NodeId {
2813 self.get_scene().with_write(
2814 |tree: &mut SceneTree| tree.create_text(content, style),
2815 NodeId::default(),
2816 )
2817 }
2818
2819 pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
2831 where
2832 F: FnMut() -> String + 'static,
2833 {
2834 let node_id: NodeId = self.text(String::new(), style);
2835 let handle: SceneHandle = self.get_scene().clone();
2836 let (scope, _): (Scope, Effect) =
2837 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
2838 self.get_scene().with_write(
2839 |tree: &mut SceneTree| {
2840 tree.attach_scope(node_id, scope);
2841 },
2842 (),
2843 );
2844 node_id
2845 }
2846
2847 pub fn scroll_view(&mut self, style: Style) -> NodeId {
2858 self.get_scene().with_write(
2859 |tree: &mut SceneTree| tree.create_scroll_view(style),
2860 NodeId::default(),
2861 )
2862 }
2863
2864 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
2876 self.get_scene().with_write(
2877 |tree: &mut SceneTree| tree.create_input(state, style),
2878 NodeId::default(),
2879 )
2880 }
2881
2882 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
2894 self.get_scene().with_write(
2895 |tree: &mut SceneTree| tree.create_image(buffer, style),
2896 NodeId::default(),
2897 )
2898 }
2899
2900 pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
2912 where
2913 F: FnMut(Rect, &mut DisplayList) + 'static,
2914 {
2915 let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
2916 self.get_scene().with_write(
2917 |tree: &mut SceneTree| tree.create_canvas(style, cb),
2918 NodeId::default(),
2919 )
2920 }
2921
2922 pub fn portal(&mut self, style: Style) -> NodeId {
2933 self.get_scene().with_write(
2934 |tree: &mut SceneTree| tree.create_portal(style),
2935 NodeId::default(),
2936 )
2937 }
2938
2939 pub fn fragment(&mut self) -> NodeId {
2949 self.get_scene().with_write(
2950 |tree: &mut SceneTree| tree.create_fragment(),
2951 NodeId::default(),
2952 )
2953 }
2954
2955 pub fn append(&mut self, parent: NodeId, child: NodeId) {
2963 self.get_scene().with_write(
2964 |tree: &mut SceneTree| {
2965 tree.append_child(parent, child);
2966 },
2967 (),
2968 );
2969 }
2970
2971 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
2979 if children.is_empty() {
2980 return;
2981 }
2982 self.get_scene().with_write(
2983 |tree: &mut SceneTree| {
2984 tree.append_children(parent, children);
2985 },
2986 (),
2987 );
2988 }
2989
2990 pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
2998 where
2999 F: FnMut() -> Style + 'static,
3000 {
3001 let handle: SceneHandle = self.get_scene().clone();
3002 let (scope, _): (Scope, Effect) =
3003 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
3004 self.get_scene().with_write(
3005 |tree: &mut SceneTree| {
3006 tree.attach_scope(node_id, scope);
3007 },
3008 (),
3009 );
3010 }
3011
3012 pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
3020 where
3021 F: FnMut(&UiEvent) + 'static,
3022 {
3023 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3024 self.get_scene().with_write(
3025 |tree: &mut SceneTree| {
3026 if let Some(node) = tree.get_node_mut(node_id) {
3027 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
3028 }
3029 },
3030 (),
3031 );
3032 }
3033
3034 pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
3042 where
3043 F: FnMut(&UiEvent) + 'static,
3044 {
3045 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3046 self.get_scene().with_write(
3047 |tree: &mut SceneTree| {
3048 if let Some(node) = tree.get_node_mut(node_id) {
3049 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
3050 }
3051 },
3052 (),
3053 );
3054 }
3055
3056 pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
3064 where
3065 F: FnMut(&UiEvent) + 'static,
3066 {
3067 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3068 self.get_scene().with_write(
3069 |tree: &mut SceneTree| {
3070 if let Some(node) = tree.get_node_mut(node_id) {
3071 node.get_mut_handlers().set_on_focus(Some(handler));
3072 node.get_mut_interaction().set_focusable(true);
3073 }
3074 },
3075 (),
3076 );
3077 }
3078
3079 pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
3087 where
3088 F: FnMut(&UiEvent) + 'static,
3089 {
3090 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3091 self.get_scene().with_write(
3092 |tree: &mut SceneTree| {
3093 if let Some(node) = tree.get_node_mut(node_id) {
3094 node.get_mut_handlers().set_on_blur(Some(handler));
3095 }
3096 },
3097 (),
3098 );
3099 }
3100
3101 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
3109 self.get_scene().with_write(
3110 |tree: &mut SceneTree| {
3111 if let Some(node) = tree.get_node_mut(node_id) {
3112 node.get_mut_interaction().set_focusable(focusable);
3113 }
3114 },
3115 (),
3116 );
3117 }
3118
3119 pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
3127 where
3128 F: FnMut(&UiEvent) + 'static,
3129 {
3130 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3131 self.get_scene().with_write(
3132 |tree: &mut SceneTree| {
3133 if let Some(node) = tree.get_node_mut(node_id) {
3134 node.get_mut_handlers().set_on_click(Some(handler));
3135 node.get_mut_interaction().set_focusable(true);
3136 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
3137 if paint.get_cursor() == CursorIcon::Default {
3138 paint.set_cursor(CursorIcon::Pointer);
3139 }
3140 }
3141 },
3142 (),
3143 );
3144 }
3145
3146 pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
3154 where
3155 F: FnMut(&UiEvent) + 'static,
3156 {
3157 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3158 self.get_scene().with_write(
3159 |tree: &mut SceneTree| {
3160 if let Some(node) = tree.get_node_mut(node_id) {
3161 node.get_mut_handlers().set_on_change(Some(handler));
3162 }
3163 },
3164 (),
3165 );
3166 }
3167
3168 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
3176 self.get_scene().with_write(
3177 |tree: &mut SceneTree| {
3178 if let Some(node) = tree.get_node_mut(node_id) {
3179 node.set_a11y(Some(props));
3180 }
3181 },
3182 (),
3183 );
3184 }
3185
3186 pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
3194 where
3195 F: FnMut(&UiEvent) + 'static,
3196 {
3197 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3198 self.get_scene().with_write(
3199 |tree: &mut SceneTree| {
3200 if let Some(node) = tree.get_node_mut(node_id) {
3201 node.get_mut_handlers().set_on_scroll(Some(handler));
3202 }
3203 },
3204 (),
3205 );
3206 }
3207
3208 pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
3216 where
3217 F: FnMut(&UiEvent) + 'static,
3218 {
3219 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3220 self.get_scene().with_write(
3221 |tree: &mut SceneTree| {
3222 if let Some(node) = tree.get_node_mut(node_id) {
3223 node.get_mut_handlers().set_on_pointer_down(Some(handler));
3224 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
3225 if paint.get_cursor() == CursorIcon::Default {
3226 paint.set_cursor(CursorIcon::Pointer);
3227 }
3228 }
3229 },
3230 (),
3231 );
3232 }
3233
3234 pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
3242 where
3243 F: FnMut(&UiEvent) + 'static,
3244 {
3245 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3246 self.get_scene().with_write(
3247 |tree: &mut SceneTree| {
3248 if let Some(node) = tree.get_node_mut(node_id) {
3249 node.get_mut_handlers().set_on_pointer_move(Some(handler));
3250 }
3251 },
3252 (),
3253 );
3254 }
3255
3256 pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
3264 where
3265 F: FnMut(&UiEvent) + 'static,
3266 {
3267 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3268 self.get_scene().with_write(
3269 |tree: &mut SceneTree| {
3270 if let Some(node) = tree.get_node_mut(node_id) {
3271 node.get_mut_handlers().set_on_pointer_up(Some(handler));
3272 }
3273 },
3274 (),
3275 );
3276 }
3277
3278 pub fn on_pointer_cancel<F>(&mut self, node_id: NodeId, callback: F)
3286 where
3287 F: FnMut(&UiEvent) + 'static,
3288 {
3289 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3290 self.get_scene().with_write(
3291 |tree: &mut SceneTree| {
3292 if let Some(node) = tree.get_node_mut(node_id) {
3293 node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
3294 }
3295 },
3296 (),
3297 );
3298 }
3299
3300 pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
3308 where
3309 F: FnMut(&UiEvent) + 'static,
3310 {
3311 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3312 let leave_handler: UiEventHandler = handler.clone();
3313 self.get_scene().with_write(
3314 |tree: &mut SceneTree| {
3315 if let Some(node) = tree.get_node_mut(node_id) {
3316 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
3317 node.get_mut_handlers()
3318 .set_on_pointer_leave(Some(leave_handler));
3319 }
3320 },
3321 (),
3322 );
3323 }
3324
3325 pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
3333 where
3334 F: FnMut(&UiEvent) + 'static,
3335 {
3336 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
3337 self.get_scene().with_write(
3338 |tree: &mut SceneTree| {
3339 if let Some(node) = tree.get_node_mut(node_id) {
3340 node.get_mut_handlers().set_on_key_down(Some(handler));
3341 node.get_mut_interaction().set_focusable(true);
3342 }
3343 },
3344 (),
3345 );
3346 }
3347
3348 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
3357 self.get_scene()
3358 .set_virtual_scroll(node_id, scroll_y, content_height);
3359 }
3360
3361 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
3369 self.get_scene().with_write(
3370 |tree: &mut SceneTree| {
3371 tree.set_scroll_offset(node_id, offset);
3372 },
3373 (),
3374 );
3375 }
3376
3377 pub fn start_transition(&mut self, transition: NodeTransition) {
3384 self.get_scene().start_transition(transition);
3385 }
3386
3387 pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
3395 where
3396 F: FnMut() -> Vec<NodeId> + 'static,
3397 {
3398 let ctx_clone: Self = self.clone();
3399 let handle: SceneHandle = self.get_scene().clone();
3400 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3401 Effect::new(move || {
3402 let (child_scope, children): (Scope, Vec<NodeId>) =
3403 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
3404 let first_opt: Option<NodeId> = children.first().copied();
3405 handle.replace_children_safe(host, children);
3406 if let Some(first) = first_opt {
3407 handle.with_write(
3408 |tree: &mut SceneTree| {
3409 tree.attach_scope(first, child_scope);
3410 },
3411 (),
3412 );
3413 }
3414 })
3415 });
3416 self.get_scene().with_write(
3417 |tree: &mut SceneTree| {
3418 tree.attach_scope(host, scope);
3419 },
3420 (),
3421 );
3422 }
3423}
3424
3425impl Drop for ContextGuard {
3427 fn drop(&mut self) {
3433 let Self { previous } = self;
3434 let restored: Option<Context> = previous.take();
3435 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
3436 *slot.borrow_mut() = restored;
3437 });
3438 }
3439}
3440
3441impl NodeRefTarget for NodeId {
3443 fn bind_node_ref(&mut self, id: NodeId) {
3450 *self = id;
3451 }
3452}
3453
3454impl NodeRefTarget for Option<NodeId> {
3456 fn bind_node_ref(&mut self, id: NodeId) {
3463 *self = Some(id);
3464 }
3465}
3466
3467impl NodeRefTarget for Cell<NodeId> {
3469 fn bind_node_ref(&mut self, id: NodeId) {
3476 self.set(id);
3477 }
3478}
3479
3480impl NodeRefTarget for Rc<Cell<NodeId>> {
3482 fn bind_node_ref(&mut self, id: NodeId) {
3489 self.set(id);
3490 }
3491}
3492
3493impl NodeRefTarget for Cell<Option<NodeId>> {
3495 fn bind_node_ref(&mut self, id: NodeId) {
3502 self.set(Some(id));
3503 }
3504}
3505
3506impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
3508 fn bind_node_ref(&mut self, id: NodeId) {
3515 self.set(Some(id));
3516 }
3517}
3518
3519impl TextNodeContent for String {
3521 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3533 ctx.text(self, style)
3534 }
3535}
3536
3537impl TextNodeContent for &str {
3539 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3551 ctx.text(self.to_string(), style)
3552 }
3553}
3554
3555impl TextNodeContent for &String {
3557 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3569 ctx.text(self.clone(), style)
3570 }
3571}
3572
3573impl TextNodeContent for Cow<'_, str> {
3575 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3587 ctx.text(self.into_owned(), style)
3588 }
3589}
3590
3591impl<F, S> TextNodeContent for F
3593where
3594 F: FnMut() -> S + 'static,
3595 S: Into<String>,
3596{
3597 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
3609 ctx.reactive_text(style, move || self().into())
3610 }
3611}