1use super::*;
2
3impl Iterator for SceneChildIter<'_> {
5 type Item = NodeId;
6
7 #[inline]
17 fn next(&mut self) -> Option<Self::Item> {
18 let Self {
19 meta,
20 topology,
21 head,
22 tail,
23 remaining,
24 } = self;
25 if *remaining == 0 || *head == NODE_INDEX_NONE {
26 return None;
27 }
28 let idx: u32 = *head;
29 *remaining -= 1;
30 if *remaining == 0 || idx == *tail {
31 *head = NODE_INDEX_NONE;
32 *tail = NODE_INDEX_NONE;
33 } else {
34 *head = topology[idx as usize].get_next_sibling();
35 }
36 let generation: u32 = meta[idx as usize].get_generation();
37 Some(NodeId::new(idx, generation))
38 }
39
40 #[inline]
50 fn size_hint(&self) -> (usize, Option<usize>) {
51 let Self { remaining, .. } = *self;
52 (remaining, Some(remaining))
53 }
54}
55
56impl DoubleEndedIterator for SceneChildIter<'_> {
58 #[inline]
68 fn next_back(&mut self) -> Option<Self::Item> {
69 let Self {
70 meta,
71 topology,
72 head,
73 tail,
74 remaining,
75 } = self;
76 if *remaining == 0 || *tail == NODE_INDEX_NONE {
77 return None;
78 }
79 let idx: u32 = *tail;
80 *remaining -= 1;
81 if *remaining == 0 || idx == *head {
82 *head = NODE_INDEX_NONE;
83 *tail = NODE_INDEX_NONE;
84 } else {
85 *tail = topology[idx as usize].get_prev_sibling();
86 }
87 let generation: u32 = meta[idx as usize].get_generation();
88 Some(NodeId::new(idx, generation))
89 }
90}
91
92impl ExactSizeIterator for SceneChildIter<'_> {}
94
95impl Default for SceneTree {
97 fn default() -> Self {
103 let root_style: Style = Style::default()
104 .column()
105 .width(Length::Percent(100.0))
106 .height(Length::Percent(100.0));
107 let root_compact: CompactPaintStyle =
108 CompactPaintStyle::from_paint(root_style.paint_ref(), EFFECT_ID_NONE);
109 let root_sigs: (u64, u64) = compute_style_sigs(&root_style);
110 let root_node: SceneNode = SceneNode::new(1, NodeKind::View, root_style);
111 Self {
112 nodes: vec![root_node],
113 meta: vec![NodeMeta::new(1, NODE_FLAG_ALIVE, DIRTY_ALL)],
114 topology: vec![NodeTopology::default()],
115 compact_paints: vec![root_compact],
116 effect_table: EffectTable::new(),
117 free_list: Vec::new(),
118 live_count: 1,
119 live_lifecycle_count: 0,
120 root: NodeId::new(0, 1),
121 focus: FocusManager::default(),
122 revision: 1,
123 transitions: Vec::new(),
124 caret_visible: true,
125 portal_nodes: Vec::new(),
126 scroll_nodes: Vec::new(),
127 dirty_paint_nodes: Vec::new(),
128 full_damage_pending: true,
129 layout_damage_pending: true,
130 full_damage_overflow: false,
131 created_since_damage: 0,
132 extra_logical_damage: Vec::new(),
133 text_selection: None,
134 text_selection_spans: Vec::new(),
135 backdrop_blur_nodes: Vec::new(),
136 layout_invalidations: 1,
137 last_collect_composite_only: false,
138 theme_entries: HashMap::new(),
139 paint_epochs: vec![0],
140 style_sigs: vec![root_sigs],
141 has_stale_hidden_dirty: false,
142 pending_scroll_into_view: Vec::new(),
143 }
144 }
145}
146
147impl SceneTree {
149 fn live_generation(&self, id: NodeId) -> Option<u32> {
160 let meta: &NodeMeta = self.get_meta().get(id.as_usize())?;
161 ((meta.get_flags() & NODE_FLAG_ALIVE) != 0 && meta.get_generation() == id.get_generation())
162 .then_some(id.get_generation())
163 }
164
165 fn theme_entry(&self, id: NodeId) -> Option<ThemeNodeEntry> {
176 let generation: u32 = self.live_generation(id)?;
177 let Self { theme_entries, .. } = self;
178 theme_entries
179 .get(&id.get_index())
180 .copied()
181 .filter(|entry: &ThemeNodeEntry| entry.get_generation() == generation)
182 }
183
184 fn update_theme_entry<CallbackFn>(&mut self, id: NodeId, apply: CallbackFn)
192 where
193 CallbackFn: FnOnce(&mut ThemeNodeEntry),
194 {
195 let Some(generation) = self.live_generation(id) else {
196 return;
197 };
198 let Self { theme_entries, .. } = self;
199 let entry: &mut ThemeNodeEntry = theme_entries
200 .entry(id.get_index())
201 .or_insert_with(|| ThemeNodeEntry::new(generation, false, None));
202 if entry.get_generation() != generation {
203 *entry = ThemeNodeEntry::new(generation, false, None);
204 }
205 apply(entry);
206 }
207
208 pub fn set_theme_owned(&mut self, id: NodeId, owned: bool) {
216 if !owned && self.theme_entry(id).is_none() {
217 return;
218 }
219 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
220 entry.set_owned(owned);
221 });
222 }
223
224 #[must_use]
235 pub fn is_theme_owned(&self, id: NodeId) -> bool {
236 self.theme_entry(id)
237 .is_some_and(|entry: ThemeNodeEntry| entry.get_owned())
238 }
239
240 #[must_use]
251 pub fn theme_baseline(&self, id: NodeId) -> Option<ThemeBaseline> {
252 self.theme_entry(id)
253 .and_then(|entry: ThemeNodeEntry| entry.get_baseline())
254 }
255
256 pub fn set_theme_baseline(&mut self, id: NodeId, baseline: Option<ThemeBaseline>) {
264 if baseline.is_none() && self.theme_entry(id).is_none() {
265 return;
266 }
267 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
268 entry.set_baseline(baseline);
269 });
270 }
271}
272
273impl SceneTree {
275 pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
283 if self.get_node(id).is_none() {
284 return;
285 }
286 let clamped: f32 = if blur_radius.is_finite() {
287 blur_radius.clamp(0.0, 96.0)
288 } else {
289 0.0
290 };
291 let prev_radius: f32 = self.backdrop_blur_radius(id);
292 if (prev_radius - clamped).abs() <= 0.001 {
293 return;
294 }
295 if prev_radius > 0.0 {
296 self.record_node_logical_damage(id);
297 }
298 let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
299 if clamped <= 0.0 {
300 blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
301 } else if let Some(slot) = blurs
302 .iter_mut()
303 .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
304 {
305 slot.1 = clamped;
306 } else {
307 blurs.push((id, clamped));
308 }
309 let paint_copy: Option<PaintStyle> =
310 self.get_node(id).map(|node: &SceneNode| *node.paint_ref());
311 if let Some(paint) = paint_copy {
312 self.sync_node_compact_paint(id.as_usize(), &paint, clamped);
313 }
314 self.mark_dirty(id, DIRTY_PAINT);
315 }
316
317 #[must_use]
328 pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
329 for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
330 if nid == id {
331 return radius;
332 }
333 }
334 0.0
335 }
336
337 #[must_use]
347 pub fn has_backdrop_blur_nodes(&self) -> bool {
348 !self.get_backdrop_blur_nodes().is_empty()
349 }
350
351 pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
363 if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
364 return 0;
365 }
366 let clamped_scale: f32 = scale.max(0.5);
367 let blur_count: usize = self.get_backdrop_blur_nodes().len();
368 let mut dirtied: Vec<bool> = vec![false; blur_count];
369 let mut total_added: usize = 0;
370 let mut changed: bool = true;
371 while changed && !damage.get_full_damage() {
372 changed = false;
373 if damage.bounds_rect().is_none() {
374 break;
375 }
376 for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
377 if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
378 continue;
379 }
380 let Some(screen_rect) = self.node_screen_bounds(nid) else {
381 continue;
382 };
383 if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
384 continue;
385 }
386 let sigma: f32 = (blur_radius * 0.5).max(0.75);
387 let halo: f32 = (sigma * 3.0).ceil() + 2.0;
388 let sample_logical: Rect = Rect::new(
389 screen_rect.get_x() - halo,
390 screen_rect.get_y() - halo,
391 screen_rect.get_width() + halo * 2.0,
392 screen_rect.get_height() + halo * 2.0,
393 );
394 let sample_phys: Rect =
395 Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
396 let output_phys: Rect = Self::scale_logical_to_phys_rect(
397 Rect::new(
398 screen_rect.get_x() - 2.0,
399 screen_rect.get_y() - 2.0,
400 screen_rect.get_width() + 4.0,
401 screen_rect.get_height() + 4.0,
402 ),
403 clamped_scale,
404 );
405 let (rects, count): ([Rect; 8], usize) =
406 damage.normalized_rects(u32::MAX, u32::MAX);
407 let overlaps: bool = rects
408 .iter()
409 .take(count)
410 .any(|rect_bounds: &Rect| rect_bounds.intersect(sample_phys).is_some());
411 if overlaps {
412 damage.add_rect(output_phys);
413 dirtied[idx] = true;
414 total_added += 1;
415 changed = true;
416 }
417 }
418 }
419 total_added
420 }
421
422 pub fn effect_dependency_damage(
438 &self,
439 dirty_set: &mut DirtyRectSet,
440 extra_portals: &[PortalBackdropRegion],
441 viewport_w: u32,
442 viewport_h: u32,
443 scale: f32,
444 full_ratio_threshold: f32,
445 ) -> EffectDamageReport {
446 if dirty_set.get_full_frame() {
447 return EffectDamageReport::new(
448 0,
449 extra_portals.len() + self.get_backdrop_blur_nodes().len(),
450 true,
451 );
452 }
453 let mut combined: Vec<PortalBackdropRegion> =
454 Vec::with_capacity(extra_portals.len() + self.get_backdrop_blur_nodes().len());
455 combined.extend_from_slice(extra_portals);
456 for &(nid, blur_radius) in self.get_backdrop_blur_nodes().iter() {
457 if blur_radius <= 0.0 || !self.is_node_visible(nid) {
458 continue;
459 }
460 if let Some(screen_rect) = self.node_screen_bounds(nid)
461 && screen_rect.get_width() > 0.0
462 && screen_rect.get_height() > 0.0
463 {
464 let is_dirty: bool = self
465 .get_node(nid)
466 .map(|scene_node: &SceneNode| scene_node.get_dirty().get_bits() != DIRTY_NONE)
467 .unwrap_or(false);
468 combined.push(PortalBackdropRegion::new(
469 screen_rect,
470 blur_radius,
471 is_dirty,
472 ));
473 }
474 }
475 dirty_set.apply_effect_dependency_damage(
476 &combined,
477 viewport_w,
478 viewport_h,
479 scale,
480 full_ratio_threshold,
481 )
482 }
483
484 #[must_use]
494 #[inline(always)]
495 pub fn portal_nodes(&self) -> &[NodeId] {
496 let Self { portal_nodes, .. } = self;
497 portal_nodes.as_slice()
498 }
499
500 #[must_use]
510 #[inline(always)]
511 pub fn has_portal_nodes(&self) -> bool {
512 let Self { portal_nodes, .. } = self;
513 !portal_nodes.is_empty()
514 }
515
516 fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
524 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
525 let next: u16 = if is_portal {
526 meta.get_flags() | NODE_FLAG_IS_PORTAL
527 } else {
528 meta.get_flags() & !NODE_FLAG_IS_PORTAL
529 };
530 let _: &mut NodeMeta = meta.set_flags(next);
531 }
532 let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
533 if is_portal {
534 if !portals.contains(&id) {
535 portals.push(id);
536 }
537 } else if !portals.is_empty() {
538 portals.retain(|existing: &NodeId| *existing != id);
539 }
540 }
541
542 #[must_use]
552 #[inline(always)]
553 pub fn scroll_nodes(&self) -> &[NodeId] {
554 let Self { scroll_nodes, .. } = self;
555 scroll_nodes.as_slice()
556 }
557
558 #[must_use]
568 #[inline(always)]
569 pub fn has_scroll_nodes(&self) -> bool {
570 let Self { scroll_nodes, .. } = self;
571 !scroll_nodes.is_empty()
572 }
573
574 fn sync_scroll_registration(&mut self, id: NodeId, is_scroll: bool) {
582 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
583 let next: u16 = if is_scroll {
584 meta.get_flags() | NODE_FLAG_IS_SCROLL_CONTAINER
585 } else {
586 meta.get_flags() & !NODE_FLAG_IS_SCROLL_CONTAINER
587 };
588 let _: &mut NodeMeta = meta.set_flags(next);
589 }
590 let scrolls: &mut Vec<NodeId> = self.get_mut_scroll_nodes();
591 if is_scroll {
592 if !scrolls.contains(&id) {
593 scrolls.push(id);
594 }
595 } else if !scrolls.is_empty() {
596 scrolls.retain(|existing: &NodeId| *existing != id);
597 }
598 }
599
600 fn sync_node_compact_paint(&mut self, idx: usize, paint: &PaintStyle, blur: f32) {
609 let prev_effect_id: u32 = self
610 .get_compact_paints()
611 .get(idx)
612 .map(CompactPaintStyle::get_effect_id)
613 .unwrap_or(EFFECT_ID_NONE);
614 let entry: PaintEffectEntry = PaintEffectEntry::from_paint_and_blur(paint, blur);
615 let next_effect_id: u32 = self.get_mut_effect_table().update(prev_effect_id, entry);
616 let compact: CompactPaintStyle = CompactPaintStyle::from_paint(paint, next_effect_id);
617 if let Some(slot) = self.get_mut_compact_paints().get_mut(idx) {
618 *slot = compact;
619 }
620 }
621
622 #[must_use]
633 #[inline(always)]
634 pub fn compact_paint(&self, id: NodeId) -> Option<&CompactPaintStyle> {
635 let idx: usize = id.as_usize();
636 let meta: &NodeMeta = self.get_meta().get(idx)?;
637 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
638 {
639 return None;
640 }
641 self.get_compact_paints().get(idx)
642 }
643
644 #[must_use]
655 #[inline(always)]
656 pub fn paint_effect(&self, id: NodeId) -> Option<&PaintEffectEntry> {
657 let effect_id: u32 = self.compact_paint(id)?.get_effect_id();
658 self.get_effect_table().get(effect_id)
659 }
660
661 #[must_use]
671 #[inline(always)]
672 pub fn effect_table(&self) -> &EffectTable {
673 self.get_effect_table()
674 }
675
676 #[must_use]
687 #[inline(always)]
688 pub fn has_extras(&self, id: NodeId) -> bool {
689 let Some(node) = self.get_node(id) else {
690 return false;
691 };
692 node.has_extras()
693 }
694
695 #[must_use]
706 #[inline(always)]
707 pub fn has_nonzero_z_child(&self, id: NodeId) -> bool {
708 let idx: usize = id.as_usize();
709 let Some(meta) = self.get_meta().get(idx) else {
710 return false;
711 };
712 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
713 && meta.get_generation() == id.get_generation()
714 && (meta.get_flags() & NODE_FLAG_HAS_NONZERO_Z_CHILD) != 0
715 }
716
717 #[must_use]
728 #[inline(always)]
729 pub fn has_lifecycle(&self, id: NodeId) -> bool {
730 let idx: usize = id.as_usize();
731 let Some(meta) = self.get_meta().get(idx) else {
732 return false;
733 };
734 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
735 && meta.get_generation() == id.get_generation()
736 && (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
737 }
738
739 #[must_use]
750 #[inline(always)]
751 pub fn has_scope(&self, id: NodeId) -> bool {
752 let idx: usize = id.as_usize();
753 let Some(meta) = self.get_meta().get(idx) else {
754 return false;
755 };
756 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
757 && meta.get_generation() == id.get_generation()
758 && (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
759 }
760
761 #[must_use]
772 #[inline(always)]
773 pub fn children_iter(&self, parent: NodeId) -> SceneChildIter<'_> {
774 let idx: usize = parent.as_usize();
775 let valid: bool = self.get_meta().get(idx).is_some_and(|meta: &NodeMeta| {
776 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
777 && meta.get_generation() == parent.get_generation()
778 });
779 if !valid {
780 return SceneChildIter {
781 meta: self.get_meta().as_slice(),
782 topology: self.get_topology().as_slice(),
783 head: NODE_INDEX_NONE,
784 tail: NODE_INDEX_NONE,
785 remaining: 0,
786 };
787 }
788 let topo: NodeTopology = self.get_topology()[idx];
789 SceneChildIter {
790 meta: self.get_meta().as_slice(),
791 topology: self.get_topology().as_slice(),
792 head: topo.get_first_child(),
793 tail: topo.get_last_child(),
794 remaining: topo.get_child_count() as usize,
795 }
796 }
797
798 #[inline]
806 pub fn for_each_child<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
807 where
808 CallbackFn: FnMut(NodeId),
809 {
810 for child_id in self.children_iter(parent) {
811 visit(child_id);
812 }
813 }
814
815 #[inline]
823 pub fn for_each_child_rev<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
824 where
825 CallbackFn: FnMut(NodeId),
826 {
827 for child_id in self.children_iter(parent).rev() {
828 visit(child_id);
829 }
830 }
831
832 #[must_use]
843 #[inline(always)]
844 pub fn child_count(&self, parent: NodeId) -> usize {
845 let idx: usize = parent.as_usize();
846 let Some(meta) = self.get_meta().get(idx) else {
847 return 0;
848 };
849 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
850 || meta.get_generation() != parent.get_generation()
851 {
852 return 0;
853 }
854 self.get_topology()[idx].get_child_count() as usize
855 }
856
857 #[must_use]
868 #[inline(always)]
869 pub fn has_children(&self, parent: NodeId) -> bool {
870 self.child_count(parent) > 0
871 }
872
873 #[must_use]
884 #[inline(always)]
885 pub fn first_child(&self, parent: NodeId) -> Option<NodeId> {
886 let idx: usize = parent.as_usize();
887 let meta: &NodeMeta = self.get_meta().get(idx)?;
888 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
889 || meta.get_generation() != parent.get_generation()
890 {
891 return None;
892 }
893 let first: u32 = self.get_topology()[idx].get_first_child();
894 if first == NODE_INDEX_NONE {
895 None
896 } else {
897 Some(NodeId::new(
898 first,
899 self.get_meta()[first as usize].get_generation(),
900 ))
901 }
902 }
903
904 #[must_use]
915 #[inline(always)]
916 pub fn last_child(&self, parent: NodeId) -> Option<NodeId> {
917 let idx: usize = parent.as_usize();
918 let meta: &NodeMeta = self.get_meta().get(idx)?;
919 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
920 || meta.get_generation() != parent.get_generation()
921 {
922 return None;
923 }
924 let last: u32 = self.get_topology()[idx].get_last_child();
925 if last == NODE_INDEX_NONE {
926 None
927 } else {
928 Some(NodeId::new(
929 last,
930 self.get_meta()[last as usize].get_generation(),
931 ))
932 }
933 }
934
935 #[must_use]
946 #[inline(always)]
947 pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
948 let idx: usize = id.as_usize();
949 let meta: &NodeMeta = self.get_meta().get(idx)?;
950 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
951 {
952 return None;
953 }
954 let next: u32 = self.get_topology()[idx].get_next_sibling();
955 if next == NODE_INDEX_NONE {
956 None
957 } else {
958 Some(NodeId::new(
959 next,
960 self.get_meta()[next as usize].get_generation(),
961 ))
962 }
963 }
964
965 #[must_use]
976 #[inline(always)]
977 pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
978 let idx: usize = id.as_usize();
979 let meta: &NodeMeta = self.get_meta().get(idx)?;
980 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
981 {
982 return None;
983 }
984 let prev: u32 = self.get_topology()[idx].get_prev_sibling();
985 if prev == NODE_INDEX_NONE {
986 None
987 } else {
988 Some(NodeId::new(
989 prev,
990 self.get_meta()[prev as usize].get_generation(),
991 ))
992 }
993 }
994
995 #[must_use]
1006 pub fn children_vec(&self, parent: NodeId) -> Vec<NodeId> {
1007 self.children_iter(parent).collect()
1008 }
1009
1010 #[must_use]
1022 pub fn is_in_subtree(&self, candidate: NodeId, root: NodeId) -> bool {
1023 if candidate == root {
1024 return true;
1025 }
1026 let mut cursor_idx: usize = candidate.as_usize();
1027 let Some(start_meta) = self.get_meta().get(cursor_idx) else {
1028 return false;
1029 };
1030 if (start_meta.get_flags() & NODE_FLAG_ALIVE) == 0
1031 || start_meta.get_generation() != candidate.get_generation()
1032 {
1033 return false;
1034 }
1035 let root_idx: u32 = root.get_index();
1036 let root_gen: u32 = root.get_generation();
1037 let max_hops: usize = self.get_topology().len();
1038 let mut hops: usize = 0;
1039 while hops < max_hops {
1040 let parent_idx: u32 = self.get_topology()[cursor_idx].get_parent();
1041 if parent_idx == NODE_INDEX_NONE {
1042 return false;
1043 }
1044 if parent_idx == root_idx
1045 && self.get_meta()[parent_idx as usize].get_generation() == root_gen
1046 {
1047 return true;
1048 }
1049 cursor_idx = parent_idx as usize;
1050 hops += 1;
1051 }
1052 false
1053 }
1054
1055 fn recompute_nonzero_z_child(&mut self, parent_idx: usize) {
1062 let mut any_nonzero: bool = false;
1063 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1064 while cur != NODE_INDEX_NONE {
1065 let ci: usize = cur as usize;
1066 if self.get_nodes()[ci].layout_ref().get_z_index() != 0 {
1067 any_nonzero = true;
1068 break;
1069 }
1070 cur = self.get_topology()[ci].get_next_sibling();
1071 }
1072 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1073 let next: u16 = if any_nonzero {
1074 meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD
1075 } else {
1076 meta.get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD
1077 };
1078 let _: &mut NodeMeta = meta.set_flags(next);
1079 }
1080 }
1081
1082 fn sync_parent_nonzero_z(&mut self, parent_idx: usize, prev_z: i32, next_z: i32) {
1091 if next_z != 0 {
1092 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1093 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1094 let _: &mut NodeMeta = meta.set_flags(next);
1095 }
1096 } else if prev_z != 0 {
1097 self.recompute_nonzero_z_child(parent_idx);
1098 }
1099 }
1100
1101 fn unlink_child_at(&mut self, parent_idx: usize, child_idx: usize) {
1109 let child_topo: NodeTopology = self.get_topology()[child_idx];
1110 if child_topo.get_parent() != parent_idx as u32 {
1111 return;
1112 }
1113 let prev: u32 = child_topo.get_prev_sibling();
1114 let next: u32 = child_topo.get_next_sibling();
1115 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1116 if prev != NODE_INDEX_NONE {
1117 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(next);
1118 } else {
1119 let _: &mut NodeTopology = topo[parent_idx].set_first_child(next);
1120 }
1121 if next != NODE_INDEX_NONE {
1122 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(prev);
1123 } else {
1124 let _: &mut NodeTopology = topo[parent_idx].set_last_child(prev);
1125 }
1126 let next_count: u32 = topo[parent_idx].get_child_count().saturating_sub(1);
1127 let _: &mut NodeTopology = topo[parent_idx].set_child_count(next_count);
1128 let _: &mut NodeTopology = topo[child_idx]
1129 .set_parent(NODE_INDEX_NONE)
1130 .set_prev_sibling(NODE_INDEX_NONE)
1131 .set_next_sibling(NODE_INDEX_NONE);
1132 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(None);
1133 let child_z: i32 = self.get_nodes()[child_idx].layout_ref().get_z_index();
1134 if child_z != 0 {
1135 self.recompute_nonzero_z_child(parent_idx);
1136 }
1137 }
1138
1139 fn link_child_tail_at(&mut self, parent_idx: usize, parent_id: NodeId, child_idx: usize) {
1148 let child_u32: u32 = child_idx as u32;
1149 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1150 let tail: u32 = topo[parent_idx].get_last_child();
1151 let _: &mut NodeTopology = topo[child_idx]
1152 .set_parent(parent_idx as u32)
1153 .set_prev_sibling(tail)
1154 .set_next_sibling(NODE_INDEX_NONE);
1155 if tail != NODE_INDEX_NONE {
1156 let _: &mut NodeTopology = topo[tail as usize].set_next_sibling(child_u32);
1157 } else {
1158 let _: &mut NodeTopology = topo[parent_idx].set_first_child(child_u32);
1159 }
1160 let next_count: u32 = topo[parent_idx].get_child_count().saturating_add(1);
1161 let _: &mut NodeTopology = topo[parent_idx]
1162 .set_last_child(child_u32)
1163 .set_child_count(next_count);
1164 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(Some(parent_id));
1165 if self.get_nodes()[child_idx].layout_ref().get_z_index() != 0 {
1166 let next_flags: u16 =
1167 self.get_meta()[parent_idx].get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1168 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(next_flags);
1169 }
1170 }
1171
1172 fn unlink_all_children_at(&mut self, parent_idx: usize) {
1179 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1180 let _: &mut NodeTopology = self.get_mut_topology()[parent_idx]
1181 .set_first_child(NODE_INDEX_NONE)
1182 .set_last_child(NODE_INDEX_NONE)
1183 .set_child_count(0);
1184 let cleared: u16 = self.get_meta()[parent_idx].get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD;
1185 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(cleared);
1186 while cur != NODE_INDEX_NONE {
1187 let ci: usize = cur as usize;
1188 let next: u32 = self.get_topology()[ci].get_next_sibling();
1189 let _: &mut NodeTopology = self.get_mut_topology()[ci]
1190 .set_parent(NODE_INDEX_NONE)
1191 .set_prev_sibling(NODE_INDEX_NONE)
1192 .set_next_sibling(NODE_INDEX_NONE);
1193 let _: &mut SceneNode = self.get_mut_nodes()[ci].set_parent(None);
1194 cur = next;
1195 }
1196 }
1197
1198 pub fn set_children_detached(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
1210 if self.get_node(parent).is_none() {
1211 return false;
1212 }
1213 if self.child_count(parent) == new_children.len()
1214 && self.children_iter(parent).eq(new_children.iter().copied())
1215 {
1216 return false;
1217 }
1218 self.clear_subtree_hover(parent);
1219 let parent_idx: usize = parent.as_usize();
1220 self.unlink_all_children_at(parent_idx);
1221 for child in new_children.iter().copied() {
1222 if child == parent || self.get_node(child).is_none() {
1223 continue;
1224 }
1225 let child_idx: usize = child.as_usize();
1226 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1227 if prev_parent != NODE_INDEX_NONE {
1228 self.unlink_child_at(prev_parent as usize, child_idx);
1229 }
1230 self.link_child_tail_at(parent_idx, parent, child_idx);
1231 }
1232 let dirty_lay: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1233 let dirty_child: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
1234 self.mark_dirty(parent, dirty_lay | dirty_child);
1235 true
1236 }
1237
1238 pub fn replace_child(&mut self, parent: NodeId, old_child: NodeId, new_child: NodeId) -> bool {
1251 if old_child == new_child || new_child == parent {
1252 return false;
1253 }
1254 if self.get_node(parent).is_none()
1255 || self.get_node(old_child).is_none()
1256 || self.get_node(new_child).is_none()
1257 {
1258 return false;
1259 }
1260 let parent_idx: usize = parent.as_usize();
1261 let old_idx: usize = old_child.as_usize();
1262 let new_idx: usize = new_child.as_usize();
1263 if self.get_topology()[old_idx].get_parent() != parent_idx as u32 {
1264 return false;
1265 }
1266 self.clear_subtree_hover(old_child);
1267 let prev_parent: u32 = self.get_topology()[new_idx].get_parent();
1268 if prev_parent != NODE_INDEX_NONE {
1269 self.unlink_child_at(prev_parent as usize, new_idx);
1270 }
1271 let old_topo: NodeTopology = self.get_topology()[old_idx];
1272 let prev: u32 = old_topo.get_prev_sibling();
1273 let next: u32 = old_topo.get_next_sibling();
1274 let new_u32: u32 = new_idx as u32;
1275 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1276 if prev != NODE_INDEX_NONE {
1277 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(new_u32);
1278 } else {
1279 let _: &mut NodeTopology = topo[parent_idx].set_first_child(new_u32);
1280 }
1281 if next != NODE_INDEX_NONE {
1282 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(new_u32);
1283 } else {
1284 let _: &mut NodeTopology = topo[parent_idx].set_last_child(new_u32);
1285 }
1286 let _: &mut NodeTopology = topo[new_idx]
1287 .set_parent(parent_idx as u32)
1288 .set_prev_sibling(prev)
1289 .set_next_sibling(next);
1290 let _: &mut NodeTopology = topo[old_idx]
1291 .set_parent(NODE_INDEX_NONE)
1292 .set_prev_sibling(NODE_INDEX_NONE)
1293 .set_next_sibling(NODE_INDEX_NONE);
1294 let _: &mut SceneNode = self.get_mut_nodes()[old_idx].set_parent(None);
1295 let _: &mut SceneNode = self.get_mut_nodes()[new_idx].set_parent(Some(parent));
1296 let old_z: i32 = self.get_nodes()[old_idx].layout_ref().get_z_index();
1297 let new_z: i32 = self.get_nodes()[new_idx].layout_ref().get_z_index();
1298 self.sync_parent_nonzero_z(parent_idx, old_z, new_z);
1299 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1300 true
1301 }
1302
1303 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
1315 let is_portal: bool = matches!(kind, NodeKind::Portal)
1316 || style.layout_ref().get_position() == Position::Fixed;
1317 let is_scroll: bool = matches!(kind, NodeKind::ScrollView)
1318 || style.layout_ref().get_overflow() == Overflow::Scroll;
1319 let mut init_flags: u16 = NODE_FLAG_ALIVE;
1320 if is_portal {
1321 init_flags |= NODE_FLAG_IS_PORTAL;
1322 }
1323 if is_scroll {
1324 init_flags |= NODE_FLAG_IS_SCROLL_CONTAINER;
1325 }
1326 let effect_entry: PaintEffectEntry =
1327 PaintEffectEntry::from_paint_and_blur(style.paint_ref(), 0.0);
1328 let effect_id: u32 = self.get_mut_effect_table().insert(effect_entry);
1329 let compact_paint: CompactPaintStyle =
1330 CompactPaintStyle::from_paint(style.paint_ref(), effect_id);
1331 let init_sigs: (u64, u64) = compute_style_sigs(&style);
1332 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
1333 let slot_idx: usize = index as usize;
1334 let slot: &mut SceneNode = &mut self.get_mut_nodes()[slot_idx];
1335 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
1336 *slot = SceneNode::new(next_gen, kind, style);
1337 self.get_mut_meta()[slot_idx] = NodeMeta::new(next_gen, init_flags, DIRTY_ALL);
1338 self.get_mut_topology()[slot_idx] = NodeTopology::default();
1339 self.get_mut_compact_paints()[slot_idx] = compact_paint;
1340 if let Some(ep) = self.get_mut_paint_epochs().get_mut(slot_idx) {
1341 *ep = ep.wrapping_add(1);
1342 }
1343 if let Some(sigs) = self.get_mut_style_sigs().get_mut(slot_idx) {
1344 *sigs = init_sigs;
1345 }
1346 NodeId::new(index, next_gen)
1347 } else {
1348 let index: u32 = self.get_nodes().len() as u32;
1349 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
1350 self.get_mut_meta()
1351 .push(NodeMeta::new(1, init_flags, DIRTY_ALL));
1352 self.get_mut_topology().push(NodeTopology::default());
1353 self.get_mut_compact_paints().push(compact_paint);
1354 self.get_mut_paint_epochs().push(0);
1355 self.get_mut_style_sigs().push(init_sigs);
1356 NodeId::new(index, 1)
1357 };
1358 if is_portal {
1359 self.get_mut_portal_nodes().push(id);
1360 self.set_full_damage_pending(true);
1361 self.clear_dirty_paint_queue();
1362 }
1363 if is_scroll {
1364 self.get_mut_scroll_nodes().push(id);
1365 }
1366 let next_live: usize = self.get_live_count().saturating_add(1);
1367 self.set_live_count(next_live);
1368 let next_created: usize = self.get_created_since_damage().saturating_add(1);
1369 self.set_created_since_damage(next_created);
1370 self.set_layout_damage_pending(true);
1371 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
1372 if next_created > DIRTY_PAINT_FULL_THRESHOLD {
1373 self.set_full_damage_pending(true);
1374 self.set_full_damage_overflow(true);
1375 self.clear_dirty_paint_queue();
1376 } else if !self.get_full_damage_pending() {
1377 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1378 self.set_full_damage_pending(true);
1379 self.set_full_damage_overflow(true);
1380 self.clear_dirty_paint_queue();
1381 } else {
1382 self.get_mut_dirty_paint_nodes().push(id);
1383 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1384 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
1385 let _: &mut NodeMeta = meta.set_flags(next_flags);
1386 }
1387 }
1388 }
1389 let next_rev: u64 = self.get_revision().wrapping_add(1);
1390 self.set_revision(next_rev);
1391 notify_frame_needed();
1392 id
1393 }
1394
1395 pub fn create_view(&mut self, style: Style) -> NodeId {
1406 self.create_node(NodeKind::View, style)
1407 }
1408
1409 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
1421 self.create_node(NodeKind::Text(content), style)
1422 }
1423
1424 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1436 self.create_node(NodeKind::Input(state), style)
1437 }
1438
1439 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1451 self.create_node(NodeKind::Image(buffer), style)
1452 }
1453
1454 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
1465 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
1466 }
1467
1468 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
1480 self.create_canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
1481 }
1482
1483 pub fn create_canvas_with_caching(
1496 &mut self,
1497 style: Style,
1498 caching: CanvasCaching,
1499 painter: CanvasDrawCallback,
1500 ) -> NodeId {
1501 let id: NodeId = self.create_node(NodeKind::Canvas(caching), style);
1502 if let Some(node) = self.get_node_mut(id) {
1503 node.set_canvas_painter(Some(painter));
1504 }
1505 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1506 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
1507 let _: &mut NodeMeta = meta.set_flags(next);
1508 }
1509 id
1510 }
1511
1512 pub fn create_portal(&mut self, style: Style) -> NodeId {
1523 self.create_node(NodeKind::Portal, style)
1524 }
1525
1526 pub fn create_fragment(&mut self) -> NodeId {
1536 self.create_node(NodeKind::Fragment, Style::default())
1537 }
1538
1539 #[must_use]
1550 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
1551 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
1552 if node.get_alive() && node.get_generation() == id.get_generation() {
1553 Some(node)
1554 } else {
1555 None
1556 }
1557 }
1558
1559 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
1570 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
1571 if node.get_alive() && node.get_generation() == id.get_generation() {
1572 Some(node)
1573 } else {
1574 None
1575 }
1576 }
1577
1578 #[must_use]
1588 #[inline(always)]
1589 pub fn live_node_count(&self) -> usize {
1590 self.get_live_count()
1591 }
1592
1593 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
1601 if parent == child || self.get_node(parent).is_none() || self.get_node(child).is_none() {
1602 return;
1603 }
1604 let parent_idx: usize = parent.as_usize();
1605 let child_idx: usize = child.as_usize();
1606 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1607 if let Some(old_parent) = prev_parent {
1608 if old_parent != parent {
1609 self.record_subtree_logical_damage(child);
1610 }
1611 self.unlink_child_at(old_parent.as_usize(), child_idx);
1612 if old_parent != parent {
1613 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1614 }
1615 }
1616 self.link_child_tail_at(parent_idx, parent, child_idx);
1617 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1618 }
1619
1620 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
1628 if children.is_empty() || self.get_node(parent).is_none() {
1629 return;
1630 }
1631 let parent_idx: usize = parent.as_usize();
1632 let mut attached_any: bool = false;
1633 for child in children.iter().copied() {
1634 if child == parent || self.get_node(child).is_none() {
1635 continue;
1636 }
1637 let child_idx: usize = child.as_usize();
1638 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1639 if let Some(old_parent) = prev_parent {
1640 if old_parent != parent {
1641 self.record_subtree_logical_damage(child);
1642 }
1643 self.unlink_child_at(old_parent.as_usize(), child_idx);
1644 if old_parent != parent {
1645 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1646 }
1647 }
1648 self.link_child_tail_at(parent_idx, parent, child_idx);
1649 attached_any = true;
1650 }
1651 if attached_any {
1652 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1653 }
1654 }
1655
1656 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
1664 if self.get_node(parent).is_none() {
1665 return;
1666 }
1667 let parent_idx: usize = parent.as_usize();
1668 let old_children: Vec<NodeId> = self.children_vec(parent);
1669 self.unlink_all_children_at(parent_idx);
1670 if new_children.is_empty() {
1671 for old_child in old_children.into_iter() {
1672 self.dispose_subtree(old_child);
1673 }
1674 } else if old_children.len() > 16 && new_children.len() > 16 {
1675 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1676 for old_child in old_children.into_iter() {
1677 if !keep_set.contains(&old_child) {
1678 self.dispose_subtree(old_child);
1679 }
1680 }
1681 } else {
1682 for old_child in old_children.into_iter() {
1683 if !new_children.contains(&old_child) {
1684 self.dispose_subtree(old_child);
1685 }
1686 }
1687 }
1688 for child in new_children.into_iter() {
1689 if child == parent || self.get_node(child).is_none() {
1690 continue;
1691 }
1692 let child_idx: usize = child.as_usize();
1693 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1694 if prev_parent != NODE_INDEX_NONE {
1695 self.unlink_child_at(prev_parent as usize, child_idx);
1696 }
1697 self.link_child_tail_at(parent_idx, parent, child_idx);
1698 }
1699 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1700 }
1701
1702 #[inline]
1713 fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
1714 let same_static: bool = prev.background_color() == next.background_color()
1715 && prev.background_gradient() == next.background_gradient()
1716 && prev.get_border() == next.get_border()
1717 && prev.get_radius() == next.get_radius()
1718 && prev.box_shadow() == next.box_shadow()
1719 && prev.focus_ring_border() == next.focus_ring_border()
1720 && prev.get_cursor() == next.get_cursor()
1721 && prev.get_pointer_events() == next.get_pointer_events();
1722 let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
1723 let composite_changed: bool = prev.get_transform() != next.get_transform()
1724 || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
1725 same_static && same_vis && composite_changed
1726 }
1727
1728 #[inline]
1740 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
1741 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
1742 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
1743 if layout_changed || text_metrics_changed {
1744 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
1745 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
1746 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
1747 Some(next_fixed)
1748 } else {
1749 None
1750 };
1751 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1752 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
1753 let mask: u16 = layout_bits | visual_bits;
1754 return (mask, portal_update);
1755 }
1756 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
1757 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
1758 if paint_changed && !text_visual_changed {
1759 if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
1760 return (DIRTY_COMPOSITE, None);
1761 }
1762 return (DIRTY_PAINT, None);
1763 }
1764 if paint_changed || text_visual_changed {
1765 (DIRTY_PAINT, None)
1766 } else {
1767 (DIRTY_NONE, None)
1768 }
1769 }
1770
1771 #[inline]
1782 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
1783 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
1784 let transform_changed: bool = prev.get_transform() != next.get_transform();
1785 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
1786 let focus_removed: bool =
1787 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
1788 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
1789 let flag_value: bool = shadow_changed || transform_changed;
1790 let is_matched: bool = border_shrank || focus_removed;
1791 let ab: bool = flag_value || is_matched;
1792 ab || opacity_toggled_zero
1793 }
1794
1795 pub fn set_style(&mut self, id: NodeId, style: Style) {
1803 let has_children: bool = self.has_children(id);
1804 let Some(node) = self.get_node(id) else {
1805 return;
1806 };
1807 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
1808 let is_scroll_kind: bool = matches!(node.get_kind(), NodeKind::ScrollView);
1809 let prev: &Style = node.style_ref();
1810 let (dirty_mask, portal_update): (u16, Option<bool>) =
1811 Self::diff_style_change(prev, &style, is_portal_kind);
1812 if dirty_mask == DIRTY_NONE {
1813 return;
1814 }
1815 let prev_scroll: bool =
1816 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1817 let next_scroll: bool =
1818 is_scroll_kind || style.layout_ref().get_overflow() == Overflow::Scroll;
1819 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1820 Some(next_scroll)
1821 } else {
1822 None
1823 };
1824 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
1825 let subtree_hidden: bool = pre_paint
1826 && (prev.paint_ref().get_opacity() > 0.0) != (style.paint_ref().get_opacity() > 0.0)
1827 && has_children;
1828 let prev_z: i32 = prev.layout_ref().get_z_index();
1829 let parent_idx: u32 = self.get_topology()[id.as_usize()].get_parent();
1830 if subtree_hidden {
1831 self.record_subtree_logical_damage(id);
1832 } else if pre_paint {
1833 self.record_node_logical_damage(id);
1834 }
1835 let hiding_now: bool = style.layout_ref().get_display() == Display::None
1836 || style.paint_ref().get_opacity() <= 0.001
1837 || style.paint_ref().get_pointer_events() == PointerEvents::None;
1838 let next_z: i32 = style.layout_ref().get_z_index();
1839 let next_paint: PaintStyle = *style.paint_ref();
1840 if let Some(node) = self.get_node_mut(id) {
1841 node.set_style(style);
1842 }
1843 let blur: f32 = self.backdrop_blur_radius(id);
1844 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1845 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1846 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1847 }
1848 if hiding_now {
1849 self.clear_subtree_hover(id);
1850 }
1851 if let Some(is_portal) = portal_update {
1852 self.sync_portal_registration(id, is_portal);
1853 }
1854 if let Some(is_scroll) = scroll_update {
1855 self.sync_scroll_registration(id, is_scroll);
1856 }
1857 self.mark_dirty(id, dirty_mask);
1858 }
1859
1860 pub fn mutate_style<CallbackFn>(&mut self, id: NodeId, mutator: CallbackFn) -> bool
1872 where
1873 CallbackFn: FnOnce(&mut Style),
1874 {
1875 let has_children: bool = self.has_children(id);
1876 let prev_opt: Option<(Style, bool, bool, u32)> =
1877 self.get_node(id).map(|node: &SceneNode| {
1878 (
1879 *node.style_ref(),
1880 matches!(node.get_kind(), NodeKind::Portal),
1881 matches!(node.get_kind(), NodeKind::ScrollView),
1882 self.get_topology()[id.as_usize()].get_parent(),
1883 )
1884 });
1885 let Some((prev, is_portal_kind, is_scroll_kind, parent_idx)) = prev_opt else {
1886 return false;
1887 };
1888 let mut next: Style = prev;
1889 mutator(&mut next);
1890 let (dirty_mask, portal_update): (u16, Option<bool>) =
1891 Self::diff_style_change(&prev, &next, is_portal_kind);
1892 if dirty_mask == DIRTY_NONE {
1893 return false;
1894 }
1895 let prev_scroll: bool =
1896 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1897 let next_scroll: bool =
1898 is_scroll_kind || next.layout_ref().get_overflow() == Overflow::Scroll;
1899 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1900 Some(next_scroll)
1901 } else {
1902 None
1903 };
1904 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
1905 if pre_paint {
1906 let opacity_toggled_zero: bool =
1907 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
1908 if opacity_toggled_zero && has_children {
1909 self.record_subtree_logical_damage(id);
1910 } else {
1911 self.record_node_logical_damage(id);
1912 }
1913 }
1914 let hiding_now: bool = next.layout_ref().get_display() == Display::None
1915 || next.paint_ref().get_opacity() <= 0.001
1916 || next.paint_ref().get_pointer_events() == PointerEvents::None;
1917 let prev_z: i32 = prev.layout_ref().get_z_index();
1918 let next_z: i32 = next.layout_ref().get_z_index();
1919 let next_paint: PaintStyle = *next.paint_ref();
1920 if let Some(node) = self.get_node_mut(id) {
1921 node.set_style(next);
1922 }
1923 let blur: f32 = self.backdrop_blur_radius(id);
1924 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1925 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1926 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1927 }
1928 if hiding_now {
1929 self.clear_subtree_hover(id);
1930 }
1931 if let Some(is_portal) = portal_update {
1932 self.sync_portal_registration(id, is_portal);
1933 }
1934 if let Some(is_scroll) = scroll_update {
1935 self.sync_scroll_registration(id, is_scroll);
1936 }
1937 self.mark_dirty(id, dirty_mask);
1938 true
1939 }
1940
1941 pub fn set_text(&mut self, id: NodeId, text: String) {
1949 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1950 Some(node) => {
1951 let layout: &LayoutStyle = node.style_ref().layout_ref();
1952 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
1953 && matches!(layout.get_height(), Length::Px(_));
1954 match node.get_mut_kind() {
1955 NodeKind::Text(current) => {
1956 if *current == text {
1957 (false, has_fixed)
1958 } else {
1959 *current = text;
1960 (true, has_fixed)
1961 }
1962 }
1963 _ => (false, false),
1964 }
1965 }
1966 None => (false, false),
1967 };
1968 if changed {
1969 let mask: u16 = if fixed_size {
1970 DIRTY_PAINT
1971 } else {
1972 DIRTY_TEXT_CHANGE_MASK
1973 };
1974 self.mark_dirty(id, mask);
1975 }
1976 }
1977
1978 pub fn set_image(&mut self, id: NodeId, buffer: ImageBuffer) {
1986 let changed: bool = match self.get_node_mut(id) {
1987 Some(node) => {
1988 let same: bool = match node.get_mut_kind() {
1989 NodeKind::Image(existing) => *existing == buffer,
1990 _ => false,
1991 };
1992 if same {
1993 false
1994 } else {
1995 *node.get_mut_kind() = NodeKind::Image(buffer);
1996 true
1997 }
1998 }
1999 None => false,
2000 };
2001 if changed {
2002 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2003 self.mark_dirty(id, dirty_l | DIRTY_PAINT);
2004 notify_frame_needed();
2005 }
2006 }
2007
2008 pub fn set_text_str(&mut self, id: NodeId, text: &str) {
2016 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2017 Some(node) => {
2018 let layout: &LayoutStyle = node.style_ref().layout_ref();
2019 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
2020 && matches!(layout.get_height(), Length::Px(_));
2021 match node.get_mut_kind() {
2022 NodeKind::Text(current) => {
2023 if current.as_str() == text {
2024 (false, has_fixed)
2025 } else {
2026 current.clear();
2027 current.push_str(text);
2028 (true, has_fixed)
2029 }
2030 }
2031 _ => (false, false),
2032 }
2033 }
2034 None => (false, false),
2035 };
2036 if changed {
2037 let mask: u16 = if fixed_size {
2038 DIRTY_PAINT
2039 } else {
2040 DIRTY_TEXT_CHANGE_MASK
2041 };
2042 self.mark_dirty(id, mask);
2043 }
2044 }
2045
2046 pub fn mutate_text<CallbackFn>(&mut self, id: NodeId, mutate: CallbackFn)
2054 where
2055 CallbackFn: FnOnce(&mut String),
2056 {
2057 let (updated, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2058 Some(node) => {
2059 let layout: &LayoutStyle = node.style_ref().layout_ref();
2060 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
2061 && matches!(layout.get_height(), Length::Px(_));
2062 match node.get_mut_kind() {
2063 NodeKind::Text(current) => {
2064 mutate(current);
2065 (true, has_fixed)
2066 }
2067 _ => (false, false),
2068 }
2069 }
2070 None => (false, false),
2071 };
2072 if updated {
2073 let mask: u16 = if fixed_size {
2074 DIRTY_PAINT
2075 } else {
2076 DIRTY_TEXT_CHANGE_MASK
2077 };
2078 self.mark_dirty(id, mask);
2079 }
2080 }
2081
2082 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
2090 let changed: bool = match self.get_node_mut(id) {
2091 Some(node) => {
2092 let layout_box: LayoutBox = node.get_layout_box();
2093 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
2094 && layout_box.get_content_size().get_height() <= 0.0
2095 && layout_box.get_content_bounds().get_width() <= 0.0
2096 && layout_box.get_content_bounds().get_height() <= 0.0;
2097 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
2098 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
2099 } else {
2100 let max_x: f32 = (layout_box.get_content_size().get_width()
2101 - layout_box.get_content_bounds().get_width())
2102 .max(0.0);
2103 let max_y: f32 = (layout_box.get_content_size().get_height()
2104 - layout_box.get_content_bounds().get_height())
2105 .max(0.0);
2106 Point::new(
2107 offset.get_x().clamp(0.0, max_x),
2108 offset.get_y().clamp(0.0, max_y),
2109 )
2110 };
2111 if layout_box.get_scroll_offset() == clamped {
2112 false
2113 } else {
2114 node.get_mut_layout_box().set_scroll_offset(clamped);
2115 true
2116 }
2117 }
2118 None => false,
2119 };
2120 if changed {
2121 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2122 }
2123 }
2124
2125 pub fn request_scroll_into_view(&mut self, target: NodeId) {
2132 if self.live_generation(target).is_none() {
2133 return;
2134 }
2135 let target_parent: Option<NodeId> = self.get_node(target).and_then(SceneNode::parent_id);
2136 let mut retained: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2137 retained.retain(|existing: &NodeId| {
2138 *existing != target
2139 && self.live_generation(*existing).is_some()
2140 && (target_parent.is_none()
2141 || self.get_node(*existing).and_then(SceneNode::parent_id) != target_parent)
2142 });
2143 retained.push(target);
2144 let _: &mut Self = self.set_pending_scroll_into_view(retained);
2145 self.mark_dirty(target, DIRTY_COMPOSITE);
2146 }
2147
2148 pub fn flush_scroll_into_view_requests(&mut self) -> bool {
2160 if self.get_pending_scroll_into_view().is_empty() {
2161 return false;
2162 }
2163 let requests: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2164 let mut any_scrolled: bool = false;
2165 for target in requests.into_iter() {
2166 if self.live_generation(target).is_none() {
2167 continue;
2168 }
2169 if !self.is_node_visible(target) {
2170 self.get_mut_pending_scroll_into_view().push(target);
2171 continue;
2172 }
2173 let Some(target_node) = self.get_node(target) else {
2174 continue;
2175 };
2176 let target_raw: Rect = target_node.get_layout_box().get_bounds();
2177 if target_raw.get_height() <= 0.0 && target_raw.get_width() <= 0.0 {
2178 self.get_mut_pending_scroll_into_view().push(target);
2179 continue;
2180 }
2181 let mut scroll_ancestor: Option<NodeId> = None;
2182 let mut cursor: Option<NodeId> = target_node.parent_id();
2183 while let Some(parent_id) = cursor {
2184 if let Some(parent_node) = self.get_node(parent_id) {
2185 if matches!(parent_node.get_kind(), NodeKind::ScrollView)
2186 || parent_node.style_ref().layout_ref().get_overflow() == Overflow::Scroll
2187 {
2188 scroll_ancestor = Some(parent_id);
2189 break;
2190 }
2191 cursor = parent_node.parent_id();
2192 } else {
2193 break;
2194 }
2195 }
2196 let Some(scroll_id) = scroll_ancestor else {
2197 continue;
2198 };
2199 let Some(scroll_node) = self.get_node(scroll_id) else {
2200 continue;
2201 };
2202 let scroll_box: LayoutBox = scroll_node.get_layout_box();
2203 let view_rect: Rect = scroll_box.get_content_bounds();
2204 if view_rect.get_height() <= 1.0 {
2205 self.get_mut_pending_scroll_into_view().push(target);
2206 continue;
2207 }
2208 let current_scroll: Point = scroll_box.get_scroll_offset();
2209 let visible_top: f32 = target_raw.get_y() - current_scroll.get_y();
2210 let visible_bottom: f32 = target_raw.bottom() - current_scroll.get_y();
2211 if visible_top < view_rect.get_y() || visible_bottom > view_rect.bottom() {
2212 let offset_in_content: f32 = target_raw.get_y() - view_rect.get_y();
2213 let centered_scroll_y: f32 = offset_in_content
2214 - (view_rect.get_height() - target_raw.get_height()).max(0.0) * 0.5;
2215 let before_offset: Point = current_scroll;
2216 self.set_scroll_offset(
2217 scroll_id,
2218 Point::new(current_scroll.get_x(), centered_scroll_y),
2219 );
2220 let after_offset: Point = self
2221 .get_node(scroll_id)
2222 .map(|node_ref: &SceneNode| node_ref.get_layout_box().get_scroll_offset())
2223 .unwrap_or(before_offset);
2224 if after_offset != before_offset {
2225 any_scrolled = true;
2226 }
2227 }
2228 }
2229 any_scrolled
2230 }
2231
2232 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
2241 let mut changed: bool = false;
2242 let mut prev_metrics: Option<(f32, f32)> = None;
2243 let next_metrics: (f32, f32) = (scroll_y.max(0.0), content_height.max(1.0));
2244 let mut scrollbar_bounds: Option<(Rect, f32, f32)> = None;
2245 if let Some(node) = self.get_node_mut(id) {
2246 let prev: Option<(f32, f32)> = node.virtual_scroll_metrics();
2247 prev_metrics = prev;
2248 let next: Option<(f32, f32)> = Some(next_metrics);
2249 if prev != next {
2250 changed = true;
2251 node.set_virtual_scroll(next);
2252 let raw_b: Rect = node.get_layout_box().get_bounds();
2253 let border_width: f32 = node.style_ref().paint_ref().get_border().get_width();
2254 let view_h: f32 = node
2255 .get_layout_box()
2256 .get_content_bounds()
2257 .get_height()
2258 .max(1.0);
2259 if raw_b.get_width() > 0.0 && raw_b.get_height() > 0.0 {
2260 scrollbar_bounds = Some((raw_b, border_width, view_h));
2261 }
2262 }
2263 }
2264 if changed {
2265 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2266 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
2267 let _: &mut NodeMeta = meta.set_flags(next_flags);
2268 }
2269 let show_scrollbar: bool = self
2270 .get_node(self.get_root())
2271 .map(|scene_node: &SceneNode| {
2272 let rb: Rect = scene_node.get_layout_box().get_bounds();
2273 rb.get_width().min(rb.get_height()) >= 540.0
2274 })
2275 .unwrap_or(true);
2276 if !show_scrollbar {
2277 let next_rev: u64 = self.get_revision().wrapping_add(1);
2278 self.set_revision(next_rev);
2279 } else if let Some((raw_b, bloom_width, view_h)) = scrollbar_bounds
2280 && let Some(screen_b) = self.node_screen_bounds(id)
2281 && screen_b.get_width() > 0.0
2282 && screen_b.get_height() > 0.0
2283 {
2284 let inner_y: f32 = screen_b.get_y() + bloom_width;
2285 let inner_h: f32 = (raw_b.get_height() - bloom_width * 2.0).max(1.0);
2286 let track_y: f32 = inner_y + 3.0;
2287 let track_h: f32 = (inner_h - 6.0).max(16.0);
2288 let n_max_sy: f32 = (next_metrics.1 - view_h).max(0.0);
2289 let n_ratio: f32 = (view_h / next_metrics.1.max(view_h)).clamp(0.0, 1.0);
2290 let n_thumb_h: f32 = (track_h * n_ratio).clamp(20.0_f32.min(track_h), track_h);
2291 let n_frac: f32 = if n_max_sy > 1.0 {
2292 (next_metrics.0 / n_max_sy).clamp(0.0, 1.0)
2293 } else {
2294 0.0
2295 };
2296 let ny0: f32 = track_y + (track_h - n_thumb_h) * n_frac;
2297 let ny1: f32 = ny0 + n_thumb_h;
2298 let (y0, y1): (f32, f32) = match prev_metrics {
2299 Some((py, ph)) => {
2300 let p_max_sy: f32 = (ph - view_h).max(0.0);
2301 let p_ratio: f32 = (view_h / ph.max(view_h)).clamp(0.0, 1.0);
2302 let p_thumb_h: f32 =
2303 (track_h * p_ratio).clamp(20.0_f32.min(track_h), track_h);
2304 let p_frac: f32 = if p_max_sy > 1.0 {
2305 (py / p_max_sy).clamp(0.0, 1.0)
2306 } else {
2307 0.0
2308 };
2309 let py0: f32 = track_y + (track_h - p_thumb_h) * p_frac;
2310 let py1: f32 = py0 + p_thumb_h;
2311 (py0.min(ny0) - 4.0, py1.max(ny1) + 4.0)
2312 }
2313 None => (screen_b.get_y(), screen_b.bottom()),
2314 };
2315 let clamped_y0: f32 = y0.max(screen_b.get_y());
2316 let clamped_y1: f32 = y1.min(screen_b.bottom());
2317 let strip_x: f32 = (screen_b.right() - bloom_width - 12.0).max(screen_b.get_x());
2318 let strip_w: f32 = (screen_b.right() - strip_x + 2.0).max(1.0);
2319 let strip_rect: Rect = Rect::new(
2320 strip_x,
2321 clamped_y0,
2322 strip_w,
2323 (clamped_y1 - clamped_y0).max(1.0),
2324 );
2325 if !self.get_full_damage_pending() {
2326 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2327 self.set_full_damage_pending(true);
2328 self.set_full_damage_overflow(true);
2329 self.get_mut_extra_logical_damage().clear();
2330 } else {
2331 self.get_mut_extra_logical_damage().push(strip_rect);
2332 }
2333 }
2334 let next_rev: u64 = self.get_revision().wrapping_add(1);
2335 self.set_revision(next_rev);
2336 } else {
2337 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2338 }
2339 }
2340 }
2341
2342 #[must_use]
2355 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
2356 let node: &SceneNode = self.get_node(id)?;
2357 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
2358 match self.node_scroll_and_transform(node) {
2359 Some(vals) => vals,
2360 None => return Some(Rect::default()),
2361 };
2362 let raw: Rect = node.get_layout_box().get_bounds();
2363 Some(Rect::new(
2364 raw.get_x() - off.get_x() + tx,
2365 raw.get_y() - off.get_y() + ty,
2366 raw.get_width() * sx,
2367 raw.get_height() * sy,
2368 ))
2369 }
2370
2371 #[inline]
2382 fn node_scroll_and_transform(&self, node: &SceneNode) -> Option<(Point, f32, f32, f32, f32)> {
2383 let style: &Style = node.style_ref();
2384 if style.layout_ref().get_display() == Display::None {
2385 return None;
2386 }
2387 let transform_val: Transform2D = style.paint_ref().get_transform();
2388 let mut tx: f32 = transform_val.get_translate_x();
2389 let mut ty: f32 = transform_val.get_translate_y();
2390 let sx_scale: f32 = transform_val.get_scale_x();
2391 let sy_scale: f32 = transform_val.get_scale_y();
2392 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2393 || style.layout_ref().get_position() == Position::Fixed;
2394 let mut stop_transform: bool = false;
2395 let mut scroll_x: f32 = 0.0;
2396 let mut scroll_y: f32 = 0.0;
2397 let mut cursor: Option<NodeId> = node.parent_id();
2398 while let Some(pid) = cursor {
2399 if let Some(pnode) = self.get_node(pid) {
2400 let pstyle: &Style = pnode.style_ref();
2401 if pstyle.layout_ref().get_display() == Display::None {
2402 return None;
2403 }
2404 if !stop_transform {
2405 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2406 tx += ptr.get_translate_x();
2407 ty += ptr.get_translate_y();
2408 if !start_top_layer {
2409 let off: Point = pnode.get_layout_box().get_scroll_offset();
2410 scroll_x += off.get_x();
2411 scroll_y += off.get_y();
2412 }
2413 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2414 || pstyle.layout_ref().get_position() == Position::Fixed;
2415 if parent_top_layer {
2416 stop_transform = true;
2417 }
2418 }
2419 cursor = pnode.parent_id();
2420 } else {
2421 break;
2422 }
2423 }
2424 Some((Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale))
2425 }
2426
2427 #[must_use]
2440 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
2441 let node: &SceneNode = self.get_node(id)?;
2442 let raw_bounds: Rect = node.get_layout_box().get_bounds();
2443 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
2444 return Some(Rect::default());
2445 }
2446 let style: &Style = node.style_ref();
2447 let paint: &PaintStyle = style.paint_ref();
2448 let transform_val: Transform2D = paint.get_transform();
2449 if transform_val.get_rotation_rad().abs() > 0.0001
2450 || transform_val.get_scale_x() <= 0.0
2451 || transform_val.get_scale_y() <= 0.0
2452 {
2453 return None;
2454 }
2455 let border_w: f32 = paint.get_border().get_width();
2456 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
2457 12.0
2458 } else {
2459 0.0
2460 };
2461 let mut margin: f32 = if border_w > 0.0 {
2462 10.0_f32.max(border_w + 6.0).max(focus_pad)
2463 } else {
2464 4.0_f32.max(focus_pad)
2465 };
2466 if let Some(shadow) = paint.box_shadow() {
2467 let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
2468 let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
2469 let spread: f32 = shadow.get_spread_radius().max(0.0);
2470 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
2471 margin = margin.max(blur_pad + spread + off_max + 4.0);
2472 }
2473 let backdrop_blur: f32 = self.backdrop_blur_radius(id);
2474 if backdrop_blur > 0.0 {
2475 let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
2476 let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
2477 margin = margin.max(blur_halo);
2478 }
2479 let tx: f32 = transform_val.get_translate_x();
2480 let ty: f32 = transform_val.get_translate_y();
2481 let sx: f32 = transform_val.get_scale_x();
2482 let sy: f32 = transform_val.get_scale_y();
2483 let base_rect: Rect = Rect::new(
2484 raw_bounds.get_x() - margin,
2485 raw_bounds.get_y() - margin,
2486 raw_bounds.get_width() + margin * 2.0,
2487 raw_bounds.get_height() + margin * 2.0,
2488 );
2489 let shifted_x: bool = tx != 0.0 || sx != 1.0;
2490 let shifted_y: bool = ty != 0.0 || sy != 1.0;
2491 let mut cur_rect: Rect = if shifted_x || shifted_y {
2492 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
2493 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
2494 let shifted_rect: Rect = Rect::new(
2495 raw_bounds.get_x() + tx - margin - scale_pad_x,
2496 raw_bounds.get_y() + ty - margin - scale_pad_y,
2497 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
2498 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
2499 );
2500 base_rect.union(shifted_rect)
2501 } else {
2502 base_rect
2503 };
2504 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2505 || style.layout_ref().get_position() == Position::Fixed;
2506 let mut cursor: Option<NodeId> = node.parent_id();
2507 while let Some(pid) = cursor {
2508 let Some(pnode) = self.get_node(pid) else {
2509 break;
2510 };
2511 let pstyle: &Style = pnode.style_ref();
2512 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2513 if ptr.get_rotation_rad().abs() > 0.0001
2514 || (ptr.get_scale_x() - 1.0).abs() > 0.001
2515 || (ptr.get_scale_y() - 1.0).abs() > 0.001
2516 {
2517 return None;
2518 }
2519 if !start_top_layer {
2520 let off: Point = pnode.get_layout_box().get_scroll_offset();
2521 cur_rect = Rect::new(
2522 cur_rect.get_x() - off.get_x(),
2523 cur_rect.get_y() - off.get_y(),
2524 cur_rect.get_width(),
2525 cur_rect.get_height(),
2526 );
2527 let p_ov: Overflow = pstyle.layout_ref().get_overflow();
2528 if matches!(p_ov, Overflow::Hidden | Overflow::Scroll) {
2529 let pb: Rect = pnode.get_layout_box().get_bounds();
2530 if pb.get_width() > 0.0 && pb.get_height() > 0.0 {
2531 let clip_box: Rect = Rect::new(
2532 pb.get_x() - 1.0,
2533 pb.get_y() - 1.0,
2534 pb.get_width() + 2.0,
2535 pb.get_height() + 2.0,
2536 );
2537 match cur_rect.intersect(clip_box) {
2538 Some(clipped) => cur_rect = clipped,
2539 None => return Some(Rect::default()),
2540 }
2541 }
2542 }
2543 }
2544 let ptx: f32 = ptr.get_translate_x();
2545 let pty: f32 = ptr.get_translate_y();
2546 if ptx != 0.0 || pty != 0.0 {
2547 cur_rect = Rect::new(
2548 cur_rect.get_x() + ptx,
2549 cur_rect.get_y() + pty,
2550 cur_rect.get_width(),
2551 cur_rect.get_height(),
2552 );
2553 }
2554 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2555 || pstyle.layout_ref().get_position() == Position::Fixed;
2556 if parent_top_layer {
2557 break;
2558 }
2559 cursor = pnode.parent_id();
2560 }
2561 Some(cur_rect)
2562 }
2563
2564 #[must_use]
2575 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
2576 let x0: f32 = (logical.get_x() * scale).floor();
2577 let y0: f32 = (logical.get_y() * scale).floor();
2578 let x1: f32 = (logical.right() * scale).ceil();
2579 let y1: f32 = (logical.bottom() * scale).ceil();
2580 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2581 }
2582
2583 fn record_node_logical_damage(&mut self, id: NodeId) {
2590 if self.get_full_damage_pending() {
2591 return;
2592 }
2593 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
2594 match rect_opt {
2595 Some(rect) => {
2596 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
2597 return;
2598 }
2599 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2600 self.set_full_damage_pending(true);
2601 self.set_full_damage_overflow(true);
2602 self.get_mut_extra_logical_damage().clear();
2603 } else {
2604 self.get_mut_extra_logical_damage().push(rect);
2605 }
2606 }
2607 None => {
2608 self.set_full_damage_pending(true);
2609 }
2610 }
2611 }
2612
2613 fn record_subtree_logical_damage(&mut self, root: NodeId) {
2620 if self.get_full_damage_pending() {
2621 return;
2622 }
2623 let mut stack: Vec<NodeId> = vec![root];
2624 let mut visited: usize = 0;
2625 while let Some(current) = stack.pop() {
2626 let Some(raw_bounds) = self
2627 .get_node(current)
2628 .map(|node: &SceneNode| node.layout_box_ref().get_bounds())
2629 else {
2630 continue;
2631 };
2632 visited += 1;
2633 if visited > DIRTY_PAINT_FULL_THRESHOLD {
2634 self.set_full_damage_pending(true);
2635 self.set_full_damage_overflow(true);
2636 self.get_mut_extra_logical_damage().clear();
2637 return;
2638 }
2639 for child in self.children_iter(current) {
2640 stack.push(child);
2641 }
2642 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
2643 self.record_node_logical_damage(current);
2644 if self.get_full_damage_pending() {
2645 return;
2646 }
2647 }
2648 }
2649 }
2650
2651 pub fn start_transition(&mut self, mut transition: NodeTransition) {
2658 let target: NodeId = transition.get_node();
2659 let had_active: bool = self
2660 .get_transitions()
2661 .iter()
2662 .any(|transform_val: &NodeTransition| transform_val.get_node() == target);
2663 self.get_mut_transitions()
2664 .retain(|object_transform: &NodeTransition| object_transform.get_node() != target);
2665 if had_active && let Some(node) = self.get_node(target) {
2666 let paint: PaintStyle = node.get_style().get_paint();
2667 let transform_val_primary: Transform2D = paint.get_transform();
2668 let cur_op: f32 = paint.get_opacity();
2669 let cur_tx: f32 = transform_val_primary.get_translate_x();
2670 let cur_ty: f32 = transform_val_primary.get_translate_y();
2671 let cur_sc: f32 = transform_val_primary.get_scale_x();
2672 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
2673 .hypot(transition.get_to_ty() - transition.get_from_ty())
2674 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
2675 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
2676 .hypot(transition.get_to_ty() - cur_ty)
2677 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
2678 if full_dist > 0.01 {
2679 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
2680 transition.set_duration((transition.get_duration() * ratio).max(0.05));
2681 }
2682 transition.set_from_opacity(cur_op);
2683 transition.set_from_tx(cur_tx);
2684 transition.set_from_ty(cur_ty);
2685 transition.set_from_scale(cur_sc);
2686 }
2687 self.record_node_logical_damage(target);
2688 let (opacity, transform): (f32, Transform2D) = transition.sample();
2689 let mut unhidden: bool = false;
2690 if let Some(node) = self.get_node_mut(target) {
2691 let style: &mut Style = node.get_mut_style();
2692 if !transition.get_hide_on_complete()
2693 && style.layout_ref().get_display() == Display::None
2694 {
2695 style.get_mut_layout().set_display(Display::Flex);
2696 unhidden = true;
2697 }
2698 style.get_mut_paint().set_opacity(opacity);
2699 style.get_mut_paint().set_transform(transform);
2700 }
2701 if unhidden {
2702 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2703 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2704 } else {
2705 self.mark_dirty(target, DIRTY_COMPOSITE);
2706 }
2707 self.get_mut_transitions().push(transition);
2708 }
2709
2710 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
2721 let len: usize = self.get_transitions().len();
2722 if len == 0 {
2723 return false;
2724 }
2725 let step: f32 = dt_secs.clamp(0.001, 0.05);
2726 let mut any_updated: bool = false;
2727 let mut write_idx: usize = 0;
2728 for read_idx in 0..len {
2729 let target: NodeId = self.get_transitions()[read_idx].get_node();
2730 if self.get_node(target).is_none() {
2731 continue;
2732 }
2733 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
2734 let transform_val: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
2735 let total_span: f32 = transform_val.get_delay() + transform_val.get_duration();
2736 let prev_elapsed: f32 = transform_val.get_elapsed();
2737 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
2738 transform_val.set_elapsed(next_elapsed);
2739 let is_done: bool = transform_val.is_complete();
2740 let in_hold: bool =
2741 prev_elapsed > 0.0 && next_elapsed <= transform_val.get_delay() && !is_done;
2742 if in_hold {
2743 (is_done, None, false)
2744 } else {
2745 let sampled: (f32, Transform2D) = transform_val.sample();
2746 let should_hide: bool = is_done && transform_val.get_hide_on_complete();
2747 (is_done, Some(sampled), should_hide)
2748 }
2749 };
2750 if let Some((opacity, transform)) = sample_opt {
2751 self.record_node_logical_damage(target);
2752 let mut is_portal_hide: bool = false;
2753 if let Some(node) = self.get_node_mut(target) {
2754 is_portal_hide = hide && matches!(node.get_kind(), NodeKind::Portal);
2755 let style: &mut Style = node.get_mut_style();
2756 style.get_mut_paint().set_opacity(opacity);
2757 style.get_mut_paint().set_transform(transform);
2758 if hide {
2759 style.get_mut_layout().set_display(Display::None);
2760 }
2761 }
2762 if hide {
2763 self.clear_subtree_hover(target);
2764 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2765 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2766 if is_portal_hide {
2767 self.set_full_damage_pending(true);
2768 self.clear_dirty_paint_queue();
2769 }
2770 } else {
2771 self.mark_dirty(target, DIRTY_COMPOSITE);
2772 }
2773 any_updated = true;
2774 }
2775 if !done {
2776 if write_idx != read_idx {
2777 self.get_mut_transitions().swap(write_idx, read_idx);
2778 }
2779 write_idx += 1;
2780 }
2781 }
2782 self.get_mut_transitions().truncate(write_idx);
2783 any_updated
2784 }
2785
2786 pub fn clear_subtree_hover(&mut self, root: NodeId) {
2793 let hovered_opt: Option<NodeId> = self.get_focus().hovered_node();
2794 if let Some(hovered_id) = hovered_opt
2795 && self.is_in_subtree(hovered_id, root)
2796 {
2797 self.get_mut_focus().set_hovered(None);
2798 let mut walk: Option<NodeId> = Some(hovered_id);
2799 while let Some(cur) = walk {
2800 let mut dirty_paint: bool = false;
2801 let next_parent: Option<NodeId> = if let Some(node) = self.get_node_mut(cur) {
2802 if node.get_interaction().get_hovered() {
2803 node.get_mut_interaction().set_hovered(false);
2804 dirty_paint = node.hover_paint().is_some()
2805 || node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
2806 }
2807 node.parent_id()
2808 } else {
2809 None
2810 };
2811 if dirty_paint {
2812 self.mark_dirty(cur, DIRTY_PAINT);
2813 }
2814 walk = next_parent;
2815 }
2816 }
2817 let pressed_opt: Option<NodeId> = self.get_focus().pressed_node();
2818 if let Some(pressed_id) = pressed_opt
2819 && self.is_in_subtree(pressed_id, root)
2820 {
2821 self.get_mut_focus().set_pressed(None);
2822 if let Some(node) = self.get_node_mut(pressed_id) {
2823 node.get_mut_interaction().set_pressed(false);
2824 }
2825 }
2826 let focused_opt: Option<NodeId> = self.get_focus().focused_node();
2827 if let Some(focused_id) = focused_opt
2828 && self.is_in_subtree(focused_id, root)
2829 {
2830 self.get_mut_focus().set_focused(None);
2831 if let Some(node) = self.get_node_mut(focused_id) {
2832 node.get_mut_interaction().set_focused(false);
2833 }
2834 }
2835 }
2836
2837 #[must_use]
2847 pub fn has_active_transitions(&self) -> bool {
2848 !self.get_transitions().is_empty()
2849 }
2850
2851 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
2859 let attached: bool = if let Some(node) = self.get_node_mut(id) {
2860 node.add_lifecycle(hook);
2861 true
2862 } else {
2863 false
2864 };
2865 if attached {
2866 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2867 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_LIFECYCLE;
2868 let next_flags: u16 = meta.get_flags() | add_flags;
2869 let _: &mut NodeMeta = meta.set_flags(next_flags);
2870 }
2871 let next_lc: usize = self.get_live_lifecycle_count().saturating_add(1);
2872 self.set_live_lifecycle_count(next_lc);
2873 }
2874 }
2875
2876 #[must_use]
2887 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2888 if self.get_live_lifecycle_count() == 0 {
2889 return Vec::new();
2890 }
2891 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
2892 let mut stack: Vec<NodeId> = vec![root];
2893 while let Some(current) = stack.pop() {
2894 let idx: usize = current.as_usize();
2895 let Some(meta) = self.get_meta().get(idx) else {
2896 continue;
2897 };
2898 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
2899 || meta.get_generation() != current.get_generation()
2900 {
2901 continue;
2902 }
2903 if (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0 {
2904 for hook in self.get_nodes()[idx].lifecycle_observers().into_iter() {
2905 out.push((current, hook));
2906 }
2907 }
2908 for child in self.children_iter(current).rev() {
2909 stack.push(child);
2910 }
2911 }
2912 out
2913 }
2914
2915 #[must_use]
2925 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2926 if self.get_live_lifecycle_count() == 0 {
2927 return Vec::new();
2928 }
2929 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
2930 let mut stack: Vec<NodeId> = vec![self.get_root()];
2931 while let Some(current) = stack.pop() {
2932 if let Some(node) = self.get_node(current) {
2933 if node.layout_ref().get_display() == Display::None {
2934 continue;
2935 }
2936 if (self.get_meta()[current.as_usize()].get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
2937 {
2938 for hook in node.lifecycle_observers().into_iter() {
2939 out.push((current, hook));
2940 }
2941 }
2942 for child in self.children_iter(current).rev() {
2943 stack.push(child);
2944 }
2945 }
2946 }
2947 out
2948 }
2949
2950 #[must_use]
2961 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
2962 let mut out: Vec<ScopeId> = Vec::new();
2963 let mut stack: Vec<NodeId> = vec![root];
2964 while let Some(current) = stack.pop() {
2965 let idx: usize = current.as_usize();
2966 let Some(meta) = self.get_meta().get(idx) else {
2967 continue;
2968 };
2969 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
2970 || meta.get_generation() != current.get_generation()
2971 {
2972 continue;
2973 }
2974 if (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
2975 && let Some(scope) = self.get_nodes()[idx].owned_scope()
2976 {
2977 out.push(scope.id());
2978 }
2979 for child in self.children_iter(current).rev() {
2980 stack.push(child);
2981 }
2982 }
2983 out
2984 }
2985
2986 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
2993 if self.get_transitions().is_empty() {
2994 return;
2995 }
2996 let mut ids: HashSet<NodeId> = HashSet::new();
2997 let mut stack: Vec<NodeId> = vec![root];
2998 while let Some(current) = stack.pop() {
2999 if ids.insert(current) && self.get_node(current).is_some() {
3000 for child in self.children_iter(current) {
3001 stack.push(child);
3002 }
3003 }
3004 }
3005 self.get_mut_transitions()
3006 .retain(|transform_val: &NodeTransition| !ids.contains(&transform_val.get_node()));
3007 }
3008
3009 pub fn cancel_node_transitions(&mut self, node_id: NodeId) {
3016 if self.get_transitions().is_empty() {
3017 return;
3018 }
3019 self.get_mut_transitions()
3020 .retain(|transform_val: &NodeTransition| transform_val.get_node() != node_id);
3021 }
3022
3023 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
3031 let attached: bool = if let Some(node) = self.get_node_mut(id) {
3032 if let Some(existing) = node.owned_scope() {
3033 existing.enter(|| {
3034 on_cleanup(move || {
3035 scope.dispose();
3036 });
3037 });
3038 } else {
3039 node.set_scope(Some(scope));
3040 }
3041 true
3042 } else {
3043 false
3044 };
3045 if attached && let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
3046 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_SCOPE;
3047 let next_flags: u16 = meta.get_flags() | add_flags;
3048 let _: &mut NodeMeta = meta.set_flags(next_flags);
3049 }
3050 }
3051
3052 #[must_use]
3063 #[inline(always)]
3064 pub(crate) fn node_paint_epoch(&self, id: NodeId) -> u32 {
3065 self.get_paint_epochs()
3066 .get(id.as_usize())
3067 .copied()
3068 .unwrap_or(0)
3069 }
3070
3071 #[must_use]
3081 #[inline(always)]
3082 pub(crate) fn root_has_layout_dirty(&self) -> bool {
3083 let root_id: NodeId = self.get_root();
3084 self.get_node(root_id).is_some_and(|root_node: &SceneNode| {
3085 root_node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
3086 })
3087 }
3088
3089 fn clear_dirty_paint_queue(&mut self) {
3095 let Self {
3096 dirty_paint_nodes,
3097 meta,
3098 ..
3099 } = self;
3100 for nid in dirty_paint_nodes.drain(..) {
3101 if let Some(slot_meta) = meta.get_mut(nid.as_usize()) {
3102 let next_flags: u16 = slot_meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3103 let _: &mut NodeMeta = slot_meta.set_flags(next_flags);
3104 }
3105 }
3106 }
3107
3108 pub fn mark_dirty(&mut self, id: NodeId, mut mask: u16) {
3116 let node_idx: usize = id.as_usize();
3117 if let Some(cur_sigs) = self
3118 .get_node(id)
3119 .map(|node: &SceneNode| compute_style_sigs(node.style_ref()))
3120 && let Some(slot_sigs) = self.get_mut_style_sigs().get_mut(node_idx)
3121 {
3122 let prev_sigs: (u64, u64) = *slot_sigs;
3123 if cur_sigs != prev_sigs {
3124 *slot_sigs = cur_sigs;
3125 if cur_sigs.0 != prev_sigs.0 {
3126 mask |= DIRTY_LAYOUT | DIRTY_PAINT;
3127 }
3128 if cur_sigs.1 != prev_sigs.1 {
3129 mask |= DIRTY_TEXT | DIRTY_LAYOUT;
3130 mask |= DIRTY_PAINT;
3131 }
3132 }
3133 }
3134 let check_layout_registries: bool = (mask & DIRTY_LAYOUT) != 0;
3135 let (mut parent_opt, portal_state, scroll_state, nonzero_z_state): (
3136 Option<NodeId>,
3137 Option<bool>,
3138 Option<bool>,
3139 Option<bool>,
3140 ) = match self.get_node_mut(id) {
3141 Some(node) => {
3142 node.get_mut_dirty().insert(mask);
3143 let (portal_opt, scroll_opt, nz_z_opt): (Option<bool>, Option<bool>, Option<bool>) =
3144 if check_layout_registries {
3145 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
3146 || node.layout_ref().get_position() == Position::Fixed;
3147 let is_scroll: bool = matches!(node.get_kind(), NodeKind::ScrollView)
3148 || node.layout_ref().get_overflow() == Overflow::Scroll;
3149 let has_nz_z: bool = node.layout_ref().get_z_index() != 0;
3150 (Some(is_portal), Some(is_scroll), Some(has_nz_z))
3151 } else {
3152 (None, None, None)
3153 };
3154 (node.parent_id(), portal_opt, scroll_opt, nz_z_opt)
3155 }
3156 None => return,
3157 };
3158 if (mask & (DIRTY_PAINT | DIRTY_FULL_DAMAGE_MASK)) != 0
3159 && let Some(epoch) = self.get_mut_paint_epochs().get_mut(node_idx)
3160 {
3161 *epoch = epoch.wrapping_add(1);
3162 }
3163 let prev_meta_flags: u16 = if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3164 let next_dirty: u16 = meta.get_dirty() | mask;
3165 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3166 meta.get_flags()
3167 } else {
3168 0
3169 };
3170 if let Some(is_portal) = portal_state {
3171 let was_portal: bool = (prev_meta_flags & NODE_FLAG_IS_PORTAL) != 0;
3172 if is_portal != was_portal {
3173 self.sync_portal_registration(id, is_portal);
3174 }
3175 }
3176 if let Some(is_scroll) = scroll_state {
3177 let was_scroll: bool = (prev_meta_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0;
3178 if is_scroll != was_scroll {
3179 self.sync_scroll_registration(id, is_scroll);
3180 }
3181 }
3182 if let Some(has_nz_z) = nonzero_z_state
3183 && let Some(parent_id) = parent_opt
3184 {
3185 let parent_idx: usize = parent_id.as_usize();
3186 if has_nz_z {
3187 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
3188 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
3189 let _: &mut NodeMeta = meta.set_flags(next_flags);
3190 }
3191 } else if self.has_nonzero_z_child(parent_id) {
3192 self.recompute_nonzero_z_child(parent_idx);
3193 }
3194 }
3195 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
3196 self.set_layout_damage_pending(true);
3197 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
3198 }
3199 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3200 if !self.get_full_damage_pending()
3201 && (mask & visual_mask) != 0
3202 && (prev_meta_flags & NODE_FLAG_IN_DIRTY_PAINT_QUEUE) == 0
3203 {
3204 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
3205 self.set_full_damage_pending(true);
3206 self.set_full_damage_overflow(true);
3207 self.clear_dirty_paint_queue();
3208 } else {
3209 self.get_mut_dirty_paint_nodes().push(id);
3210 if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3211 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3212 let _: &mut NodeMeta = meta.set_flags(next_flags);
3213 }
3214 }
3215 }
3216 let mut ancestor_mask: u16 = DIRTY_NONE;
3217 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
3218 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
3219 }
3220 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
3221 ancestor_mask |= DIRTY_SUBTREE_PAINT;
3222 }
3223 if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
3224 ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
3225 }
3226 if ancestor_mask != DIRTY_NONE {
3227 let root_has_mask: bool = {
3228 let root_id: NodeId = self.get_root();
3229 self.get_node(root_id)
3230 .map(|root_node: &SceneNode| {
3231 (root_node.get_dirty().get_bits() & ancestor_mask) == ancestor_mask
3232 })
3233 .unwrap_or(true)
3234 };
3235 let can_early_break: bool = root_has_mask && !self.get_has_stale_hidden_dirty();
3236 while let Some(ancestor_id) = parent_opt {
3237 let ancestor_idx: usize = ancestor_id.as_usize();
3238 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3239 let already: bool =
3240 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
3241 ancestor.get_mut_dirty().insert(ancestor_mask);
3242 parent_opt = ancestor.parent_id();
3243 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3244 let next_dirty: u16 = meta.get_dirty() | ancestor_mask;
3245 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3246 }
3247 if already && can_early_break {
3248 break;
3249 }
3250 } else {
3251 break;
3252 }
3253 }
3254 }
3255 let next_rev: u64 = self.get_revision().wrapping_add(1);
3256 self.set_revision(next_rev);
3257 notify_frame_needed();
3258 }
3259
3260 #[must_use]
3271 pub fn is_node_visible(&self, id: NodeId) -> bool {
3272 let root: NodeId = self.get_root();
3273 let mut cursor: Option<NodeId> = Some(id);
3274 while let Some(cur) = cursor {
3275 let Some(node) = self.get_node(cur) else {
3276 return false;
3277 };
3278 let style: &Style = node.style_ref();
3279 if style.get_layout().get_display() == Display::None
3280 || style.get_paint().get_opacity() <= 0.001
3281 {
3282 return false;
3283 }
3284 if cur == root {
3285 return true;
3286 }
3287 cursor = node.parent_id();
3288 }
3289 false
3290 }
3291
3292 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
3303 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
3304 damage
3305 }
3306
3307 pub(crate) fn collect_surgical_paint_damage(
3319 &mut self,
3320 scale: f32,
3321 allow_partial_layout: bool,
3322 ) -> (DamageRegion, bool) {
3323 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
3324 let layout_pending: bool = self.get_layout_damage_pending();
3325 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
3326 let no_extra: bool = self.get_extra_logical_damage().is_empty();
3327 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
3328 self.set_created_since_damage(0);
3329 self.set_last_collect_composite_only(false);
3330 return (DamageRegion::default(), false);
3331 }
3332 let mut full: bool =
3333 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
3334 let mut saw_paint_or_layout: bool = layout_pending;
3335 let mut saw_composite_or_scroll: bool = false;
3336 let mut region: DamageRegion = DamageRegion::default();
3337 if !full {
3338 let extra_len: usize = self.get_extra_logical_damage().len();
3339 for item_index in 0..extra_len {
3340 let logical_rect: Rect = self.get_extra_logical_damage()[item_index];
3341 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
3342 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3343 }
3344 }
3345 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3346 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3347 for outer_index in 0..dirty_len {
3348 let nid: NodeId = self.get_dirty_paint_nodes()[outer_index];
3349 let Some(node) = self.get_node(nid) else {
3350 continue;
3351 };
3352 let bits: u16 = node.get_dirty().get_bits();
3353 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
3354 if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
3355 saw_paint_or_layout = true;
3356 }
3357 if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
3358 saw_composite_or_scroll = true;
3359 }
3360 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
3361 full = true;
3362 break;
3363 }
3364 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
3365 full = true;
3366 break;
3367 }
3368 if (bits & visual_mask) == 0 {
3369 continue;
3370 }
3371 let raw_bounds: Rect = node.get_layout_box().get_bounds();
3372 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
3373 match self.node_conservative_logical_rect(nid) {
3374 Some(logical_rect) => {
3375 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3376 }
3377 None => {
3378 full = true;
3379 break;
3380 }
3381 }
3382 } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
3383 && !has_layout_bits
3384 && node.style_ref().layout_ref().get_display() != Display::None
3385 {
3386 full = true;
3387 break;
3388 }
3389 }
3390 }
3391 self.set_last_collect_composite_only(
3392 !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
3393 );
3394 self.set_layout_damage_pending(false);
3395 self.set_created_since_damage(0);
3396 self.get_mut_extra_logical_damage().clear();
3397 if !full {
3398 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3399 let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
3400 for step_index in 0..dirty_len {
3401 let nid: NodeId = self.get_dirty_paint_nodes()[step_index];
3402 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
3403 Some(node) => {
3404 node.get_mut_dirty().remove(clear_mask);
3405 node.parent_id()
3406 }
3407 None => None,
3408 };
3409 if let Some(meta) = self.get_mut_meta().get_mut(nid.get_index() as usize) {
3410 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3411 let next_flags: u16 = meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3412 let _: &mut NodeMeta = meta.set_dirty(next_dirty).set_flags(next_flags);
3413 }
3414 while let Some(ancestor_id) = parent_opt {
3415 let ancestor_idx: usize = ancestor_id.get_index() as usize;
3416 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3417 if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
3418 break;
3419 }
3420 ancestor.get_mut_dirty().remove(ancestor_clear);
3421 parent_opt = ancestor.parent_id();
3422 } else {
3423 break;
3424 }
3425 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3426 let next_dirty: u16 = meta.get_dirty() & !ancestor_clear;
3427 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3428 }
3429 }
3430 }
3431 self.get_mut_dirty_paint_nodes().clear();
3432 return (region, layout_pending);
3433 }
3434 self.set_full_damage_pending(false);
3435 self.clear_dirty_paint_queue();
3436 let node_count: usize = self.get_nodes().len();
3437 for idx in 0..node_count {
3438 let should_clear: bool = {
3439 let node: &SceneNode = &self.get_nodes()[idx];
3440 node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0
3441 };
3442 if should_clear {
3443 self.get_mut_nodes()[idx].get_mut_dirty().remove(clear_mask);
3444 if let Some(meta) = self.get_mut_meta().get_mut(idx) {
3445 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3446 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3447 }
3448 }
3449 }
3450 (DamageRegion::full(), layout_pending)
3451 }
3452
3453 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
3463 let was_overflow: bool = self.get_full_damage_overflow();
3464 self.set_full_damage_overflow(false);
3465 was_overflow
3466 }
3467
3468 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
3479 if id == self.get_root() || self.get_node(id).is_none() {
3480 return (Vec::new(), Vec::new());
3481 }
3482 self.record_subtree_logical_damage(id);
3483 self.cancel_subtree_transitions(id);
3484 self.clear_subtree_hover(id);
3485 let root_parent: u32 = self.get_topology()[id.as_usize()].get_parent();
3486 if root_parent != NODE_INDEX_NONE {
3487 self.unlink_child_at(root_parent as usize, id.as_usize());
3488 }
3489 let mut stack: Vec<NodeId> = vec![id];
3490 let mut scopes: Vec<Scope> = Vec::new();
3491 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3492 while let Some(current) = stack.pop() {
3493 let cur_idx: usize = current.as_usize();
3494 let mut next_child: u32 = self.get_topology()[cur_idx].get_first_child();
3495 let mut removed_lifecycles: usize = 0;
3496 let (was_alive, prev_flags): (bool, u16) = match self.get_node_mut(current) {
3497 Some(node) => {
3498 node.set_alive(false);
3499 node.set_kind(NodeKind::View);
3500 if node.has_extras() {
3501 if let Some(scope) = node.owned_scope() {
3502 scopes.push(scope);
3503 }
3504 let drained: Vec<Rc<dyn Lifecycle>> = node.take_lifecycles();
3505 removed_lifecycles = drained.len();
3506 for hook in drained.into_iter() {
3507 observers.push((current, hook));
3508 }
3509 node.clear_extras();
3510 }
3511 node.set_parent(None);
3512 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
3513 node.set_generation(next_gen);
3514 (true, self.get_meta()[cur_idx].get_flags())
3515 }
3516 None => (false, 0),
3517 };
3518 if !was_alive {
3519 continue;
3520 }
3521 while next_child != NODE_INDEX_NONE {
3522 let ci: usize = next_child as usize;
3523 let sibling: u32 = self.get_topology()[ci].get_next_sibling();
3524 let child_gen: u32 = self.get_meta()[ci].get_generation();
3525 stack.push(NodeId::new(next_child, child_gen));
3526 next_child = sibling;
3527 }
3528 let next_gen: u32 = self.get_nodes()[cur_idx].get_generation();
3529 self.get_mut_meta()[cur_idx] = NodeMeta::new(next_gen, 0, DIRTY_NONE);
3530 self.get_mut_topology()[cur_idx] = NodeTopology::default();
3531 let prev_effect_id: u32 = self.get_compact_paints()[cur_idx].get_effect_id();
3532 if prev_effect_id != EFFECT_ID_NONE {
3533 self.get_mut_effect_table().remove(prev_effect_id);
3534 let _: &mut CompactPaintStyle =
3535 self.get_mut_compact_paints()[cur_idx].set_effect_id(EFFECT_ID_NONE);
3536 }
3537 let next_live: usize = self.get_live_count().saturating_sub(1);
3538 self.set_live_count(next_live);
3539 if removed_lifecycles > 0 {
3540 let next_lc: usize = self
3541 .get_live_lifecycle_count()
3542 .saturating_sub(removed_lifecycles);
3543 self.set_live_lifecycle_count(next_lc);
3544 }
3545 if (prev_flags & NODE_FLAG_IS_PORTAL) != 0 && !self.portal_nodes().is_empty() {
3546 self.sync_portal_registration(current, false);
3547 }
3548 if (prev_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0 && !self.scroll_nodes().is_empty()
3549 {
3550 self.sync_scroll_registration(current, false);
3551 }
3552 if !self.get_backdrop_blur_nodes().is_empty() {
3553 self.get_mut_backdrop_blur_nodes()
3554 .retain(|entry: &(NodeId, f32)| entry.0 != current);
3555 }
3556 if self.get_focus().focused_node() == Some(current) {
3557 self.get_mut_focus().set_focused(None);
3558 }
3559 if self.get_focus().hovered_node() == Some(current) {
3560 self.get_mut_focus().set_hovered(None);
3561 }
3562 if self.get_focus().pressed_node() == Some(current) {
3563 self.get_mut_focus().set_pressed(None);
3564 }
3565 let sel_hits_current: bool =
3566 self.text_selection().is_some_and(|sel: SelectionState| {
3567 sel.get_anchor_node() == current || sel.get_focus_node() == current
3568 }) || self
3569 .text_selection_spans_ref()
3570 .iter()
3571 .any(|&(nid, _, _): &(NodeId, usize, usize)| nid == current);
3572 if sel_hits_current {
3573 self.set_text_selection(None);
3574 }
3575 self.get_mut_free_list().push(current.get_index());
3576 }
3577 (scopes, observers)
3578 }
3579
3580 pub fn dispose_subtree(&mut self, id: NodeId) {
3587 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
3588 finalize_disposed_subtree(scopes, observers);
3589 }
3590
3591 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
3602 let prev: Option<NodeId> = self.get_focus().focused_node();
3603 if prev == target {
3604 return Vec::new();
3605 }
3606 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
3607 if let Some(old_id) = prev {
3608 if let Some(old_node) = self.get_node_mut(old_id) {
3609 old_node.get_mut_interaction().set_focused(false);
3610 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
3611 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
3612 }
3613 }
3614 self.mark_dirty(old_id, DIRTY_PAINT);
3615 }
3616 self.get_mut_focus().set_focused(target);
3617 if let Some(new_id) = target {
3618 if let Some(new_node) = self.get_node_mut(new_id) {
3619 new_node.get_mut_interaction().set_focused(true);
3620 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
3621 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
3622 }
3623 }
3624 self.mark_dirty(new_id, DIRTY_PAINT);
3625 }
3626 callbacks
3627 }
3628
3629 #[must_use]
3640 pub fn effective_text_select_mode(&self, id: NodeId) -> TextSelectMode {
3641 let mut cursor: Option<NodeId> = Some(id);
3642 while let Some(cur) = cursor {
3643 let Some(node) = self.get_node(cur) else {
3644 return TextSelectMode::None;
3645 };
3646 if let Some(mode) = node.style_ref().text_ref().text_select_mode() {
3647 return mode;
3648 }
3649 cursor = node.parent_id();
3650 }
3651 TextSelectMode::None
3652 }
3653
3654 #[must_use]
3665 pub fn is_node_selectable(&self, id: NodeId) -> bool {
3666 self.effective_text_select_mode(id) != TextSelectMode::None
3667 }
3668
3669 #[must_use]
3680 pub(crate) fn selectable_scope_root(&self, id: NodeId) -> Option<(NodeId, TextSelectMode)> {
3681 let target_mode: TextSelectMode = self.effective_text_select_mode(id);
3682 if target_mode == TextSelectMode::None {
3683 return None;
3684 }
3685 let mut scope: NodeId = id;
3686 loop {
3687 let cur_node: &SceneNode = self.get_node(scope)?;
3688 if matches!(cur_node.get_kind(), NodeKind::Portal) {
3689 break;
3690 }
3691 let Some(parent_id) = cur_node.parent_id() else {
3692 break;
3693 };
3694 if self.effective_text_select_mode(parent_id) != target_mode {
3695 break;
3696 }
3697 scope = parent_id;
3698 }
3699 Some((scope, target_mode))
3700 }
3701
3702 #[must_use]
3713 pub(crate) fn selectable_scope_text_nodes(&self, id: NodeId) -> Vec<NodeId> {
3714 let Some((scope_root, target_mode)) = self.selectable_scope_root(id) else {
3715 return Vec::new();
3716 };
3717 let mut out: Vec<NodeId> = Vec::new();
3718 let mut stack: Vec<NodeId> = vec![scope_root];
3719 while let Some(cid) = stack.pop() {
3720 let Some(node) = self.get_node(cid) else {
3721 continue;
3722 };
3723 if !node.get_alive() || node.style_ref().get_layout().get_display() == Display::None {
3724 continue;
3725 }
3726 if cid != scope_root {
3727 if matches!(node.get_kind(), NodeKind::Portal) {
3728 continue;
3729 }
3730 if node
3731 .style_ref()
3732 .text_ref()
3733 .text_select_mode()
3734 .is_some_and(|matrix_elems: TextSelectMode| matrix_elems != target_mode)
3735 {
3736 continue;
3737 }
3738 }
3739 if matches!(node.get_kind(), NodeKind::Text(_)) {
3740 out.push(cid);
3741 } else {
3742 let start_len: usize = stack.len();
3743 stack.extend(self.children_iter(cid));
3744 stack[start_len..].reverse();
3745 }
3746 }
3747 out
3748 }
3749
3750 #[must_use]
3761 pub(crate) fn text_node_screen_content_rect(&self, node_id: NodeId) -> Option<Rect> {
3762 let node: &SceneNode = self.get_node(node_id)?;
3763 let computed_box: LayoutBox = node.get_layout_box();
3764 let outer: Rect = computed_box.get_bounds();
3765 let content_rect: Rect = computed_box.get_content_bounds();
3766 let screen_outer: Rect = self.node_screen_bounds(node_id).unwrap_or(outer);
3767 Some(Rect::new(
3768 screen_outer.get_x() + (content_rect.get_x() - outer.get_x()),
3769 screen_outer.get_y() + (content_rect.get_y() - outer.get_y()),
3770 content_rect.get_width(),
3771 content_rect.get_height(),
3772 ))
3773 }
3774
3775 #[must_use]
3787 fn is_new_visual_row(&self, prev_id: NodeId, cur_id: NodeId) -> bool {
3788 let prev_rect: Option<Rect> = self.text_node_screen_content_rect(prev_id);
3789 let cur_rect: Option<Rect> = self.text_node_screen_content_rect(cur_id);
3790 if let (Some(pr), Some(cr)) = (prev_rect, cur_rect)
3791 && pr.get_height() > 0.0
3792 && cr.get_height() > 0.0
3793 {
3794 let prev_cy: f32 = pr.get_y() + pr.get_height() * 0.5;
3795 let cur_cy: f32 = cr.get_y() + cr.get_height() * 0.5;
3796 let threshold: f32 = (pr.get_height().min(cr.get_height()) * 0.5).max(4.0);
3797 return (cur_cy - prev_cy).abs() > threshold;
3798 }
3799 let prev_parent: Option<NodeId> = self.get_node(prev_id).and_then(SceneNode::parent_id);
3800 let cur_parent: Option<NodeId> = self.get_node(cur_id).and_then(SceneNode::parent_id);
3801 if let (Some(pp), Some(cp)) = (prev_parent, cur_parent)
3802 && pp == cp
3803 && let Some(pnode) = self.get_node(pp)
3804 && pnode.style_ref().get_layout().get_flex_direction() == FlexDirection::Row
3805 {
3806 return false;
3807 }
3808 true
3809 }
3810
3811 #[must_use]
3822 fn resolve_selection_spans(&self, selection: SelectionState) -> Vec<(NodeId, usize, usize)> {
3823 if selection.is_empty() {
3824 return Vec::new();
3825 }
3826 if selection.is_single_node() {
3827 let nid: NodeId = selection.get_anchor_node();
3828 let Some(node) = self.get_node(nid) else {
3829 return Vec::new();
3830 };
3831 let NodeKind::Text(content) = node.get_kind() else {
3832 return Vec::new();
3833 };
3834 let len: usize = content.chars().count();
3835 let (raw_s, raw_e): (usize, usize) = selection.ordered_range();
3836 let start_c: usize = raw_s.min(len);
3837 let end_c: usize = raw_e.min(len);
3838 return if start_c < end_c {
3839 vec![(nid, start_c, end_c)]
3840 } else {
3841 Vec::new()
3842 };
3843 }
3844 let anchor_id: NodeId = selection.get_anchor_node();
3845 let focus_id: NodeId = selection.get_focus_node();
3846 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_id);
3847 let anchor_pos: Option<usize> = nodes
3848 .iter()
3849 .position(|target_node_id: &NodeId| *target_node_id == anchor_id);
3850 let focus_pos: Option<usize> = nodes
3851 .iter()
3852 .position(|element_id: &NodeId| *element_id == focus_id);
3853 let (Some(a_pos), Some(f_pos)) = (anchor_pos, focus_pos) else {
3854 return Vec::new();
3855 };
3856 let (start_pos, start_ch, end_pos, end_ch): (usize, usize, usize, usize) = if a_pos <= f_pos
3857 {
3858 (
3859 a_pos,
3860 selection.get_anchor_char(),
3861 f_pos,
3862 selection.get_focus_char(),
3863 )
3864 } else {
3865 (
3866 f_pos,
3867 selection.get_focus_char(),
3868 a_pos,
3869 selection.get_anchor_char(),
3870 )
3871 };
3872 let mut spans: Vec<(NodeId, usize, usize)> =
3873 Vec::with_capacity(end_pos.saturating_sub(start_pos) + 1);
3874 for (idx, &nid) in nodes.iter().enumerate().take(end_pos + 1).skip(start_pos) {
3875 let Some(node) = self.get_node(nid) else {
3876 continue;
3877 };
3878 let NodeKind::Text(content) = node.get_kind() else {
3879 continue;
3880 };
3881 let len: usize = content.chars().count();
3882 let source_val: usize = if idx == start_pos {
3883 start_ch.min(len)
3884 } else {
3885 0
3886 };
3887 let event_ref: usize = if idx == end_pos { end_ch.min(len) } else { len };
3888 if source_val < event_ref || (idx > start_pos && idx < end_pos) {
3889 spans.push((nid, source_val, event_ref));
3890 }
3891 }
3892 spans
3893 }
3894
3895 #[must_use]
3905 pub(crate) fn text_selection_spans_ref(&self) -> &[(NodeId, usize, usize)] {
3906 let Self {
3907 text_selection_spans,
3908 ..
3909 } = self;
3910 text_selection_spans.as_slice()
3911 }
3912
3913 #[must_use]
3924 pub(crate) fn text_selection_range_for(&self, id: NodeId) -> Option<(usize, usize)> {
3925 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
3926 if spans.is_empty() {
3927 return None;
3928 }
3929 for &(nid, source_val, event_ref) in spans.iter() {
3930 if nid == id {
3931 return if source_val < event_ref {
3932 Some((source_val, event_ref))
3933 } else {
3934 None
3935 };
3936 }
3937 }
3938 None
3939 }
3940
3941 #[must_use]
3953 pub(crate) fn is_descendant_of(&self, id: NodeId, ancestor: NodeId) -> bool {
3954 let mut cursor: Option<NodeId> = Some(id);
3955 while let Some(cur) = cursor {
3956 if cur == ancestor {
3957 return true;
3958 }
3959 cursor = self.get_node(cur).and_then(SceneNode::parent_id);
3960 }
3961 false
3962 }
3963
3964 #[must_use]
3975 pub fn effective_selection_color(&self, id: NodeId) -> Color {
3976 let mut cursor: Option<NodeId> = Some(id);
3977 while let Some(cur) = cursor {
3978 let Some(node) = self.get_node(cur) else {
3979 break;
3980 };
3981 if let Some(color) = node.style_ref().text_ref().selection_color() {
3982 return color;
3983 }
3984 cursor = node.parent_id();
3985 }
3986 DEFAULT_TEXT_SELECTION_COLOR
3987 }
3988
3989 #[must_use]
3999 pub fn text_selection(&self) -> Option<SelectionState> {
4000 let Self { text_selection, .. } = self;
4001 *text_selection
4002 }
4003
4004 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
4011 let prev: Option<SelectionState> = self.text_selection();
4012 if prev == selection {
4013 return;
4014 }
4015 let mut dirty_ids: Vec<NodeId> =
4016 Vec::with_capacity(self.text_selection_spans_ref().len() + 4);
4017 for &(nid, _, _) in self.text_selection_spans_ref().iter() {
4018 dirty_ids.push(nid);
4019 }
4020 if let Some(old_sel) = prev {
4021 dirty_ids.push(old_sel.get_anchor_node());
4022 if !old_sel.is_single_node() {
4023 dirty_ids.push(old_sel.get_focus_node());
4024 }
4025 }
4026 let next_spans: Vec<(NodeId, usize, usize)> = selection
4027 .map(|sel: SelectionState| self.resolve_selection_spans(sel))
4028 .unwrap_or_default();
4029 for &(nid, _, _) in next_spans.iter() {
4030 dirty_ids.push(nid);
4031 }
4032 if let Some(new_sel) = selection {
4033 dirty_ids.push(new_sel.get_anchor_node());
4034 if !new_sel.is_single_node() {
4035 dirty_ids.push(new_sel.get_focus_node());
4036 }
4037 }
4038 let Self {
4039 text_selection,
4040 text_selection_spans,
4041 ..
4042 } = self;
4043 *text_selection = selection;
4044 *text_selection_spans = next_spans;
4045 for nid in dirty_ids.into_iter() {
4046 self.mark_dirty(nid, DIRTY_PAINT);
4047 }
4048 }
4049
4050 pub fn clear_text_selection(&mut self) {
4056 self.set_text_selection(None);
4057 }
4058
4059 #[must_use]
4070 fn extract_selected_text_filtered(&self, container: Option<NodeId>) -> Option<String> {
4071 let sel: SelectionState = self.text_selection()?;
4072 if sel.is_empty() {
4073 return None;
4074 }
4075 if let Some(root) = container
4076 && !self.is_descendant_of(sel.get_anchor_node(), root)
4077 {
4078 return None;
4079 }
4080 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4081 if spans.is_empty() {
4082 return None;
4083 }
4084 if spans.len() == 1 {
4085 let (nid, source_val, event_ref): (NodeId, usize, usize) = spans[0];
4086 if let Some(root) = container
4087 && !self.is_descendant_of(nid, root)
4088 {
4089 return None;
4090 }
4091 let node: &SceneNode = self.get_node(nid)?;
4092 let NodeKind::Text(content) = node.get_kind() else {
4093 return None;
4094 };
4095 let extracted: &str = extract_char_range(content.as_str(), source_val, event_ref);
4096 return if extracted.is_empty() {
4097 None
4098 } else {
4099 Some(extracted.to_string())
4100 };
4101 }
4102 let mut out: String = String::new();
4103 let mut prev_emitted_node: Option<NodeId> = None;
4104 let last_span_idx: usize = spans.len().saturating_sub(1);
4105 for (idx, &(nid, scale_val, error_val)) in spans.iter().enumerate() {
4106 if let Some(root) = container
4107 && !self.is_descendant_of(nid, root)
4108 {
4109 continue;
4110 }
4111 let Some(node) = self.get_node(nid) else {
4112 continue;
4113 };
4114 let NodeKind::Text(content) = node.get_kind() else {
4115 continue;
4116 };
4117 let part: &str = extract_char_range(content.as_str(), scale_val, error_val);
4118 let is_middle_empty: bool = part.is_empty() && idx > 0 && idx < last_span_idx;
4119 if part.is_empty() && !is_middle_empty {
4120 continue;
4121 }
4122 if let Some(prev_id) = prev_emitted_node
4123 && self.is_new_visual_row(prev_id, nid)
4124 {
4125 out.push('\n');
4126 }
4127 out.push_str(part);
4128 prev_emitted_node = Some(nid);
4129 }
4130 if out.is_empty() { None } else { Some(out) }
4131 }
4132
4133 #[must_use]
4143 pub fn get_selected_text(&self) -> Option<String> {
4144 if let Some(sel) = self.extract_selected_text_filtered(None) {
4145 return Some(sel);
4146 }
4147 let focused: NodeId = self.get_focus().focused_node()?;
4148 let node: &SceneNode = self.get_node(focused)?;
4149 if let NodeKind::Input(state) = node.get_kind() {
4150 return state.selected_text().map(str::to_string);
4151 }
4152 None
4153 }
4154
4155 #[must_use]
4166 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4167 self.extract_selected_text_filtered(Some(container))
4168 }
4169
4170 pub fn select_all_text(&mut self, id: NodeId) -> bool {
4181 if !self.is_node_selectable(id) {
4182 return false;
4183 }
4184 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4185 let Some(&first_id) = nodes.first() else {
4186 return false;
4187 };
4188 let Some(&last_id) = nodes.last() else {
4189 return false;
4190 };
4191 let last_len: usize = self
4192 .get_node(last_id)
4193 .and_then(|node: &SceneNode| {
4194 if let NodeKind::Text(content) = node.get_kind() {
4195 Some(content.chars().count())
4196 } else {
4197 None
4198 }
4199 })
4200 .unwrap_or(0);
4201 if nodes.len() == 1 && last_len == 0 {
4202 return false;
4203 }
4204 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4205 true
4206 }
4207
4208 pub(crate) fn select_line_text(&mut self, id: NodeId) -> bool {
4219 if !self.is_node_selectable(id) {
4220 return false;
4221 }
4222 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4223 let Some(pos) = nodes
4224 .iter()
4225 .position(|target_node_id: &NodeId| *target_node_id == id)
4226 else {
4227 return false;
4228 };
4229 let mut start_idx: usize = pos;
4230 while start_idx > 0 && !self.is_new_visual_row(nodes[start_idx - 1], id) {
4231 start_idx -= 1;
4232 }
4233 let mut end_idx: usize = pos;
4234 while end_idx + 1 < nodes.len() && !self.is_new_visual_row(id, nodes[end_idx + 1]) {
4235 end_idx += 1;
4236 }
4237 let first_id: NodeId = nodes[start_idx];
4238 let last_id: NodeId = nodes[end_idx];
4239 let last_len: usize = self
4240 .get_node(last_id)
4241 .and_then(|node: &SceneNode| {
4242 if let NodeKind::Text(content) = node.get_kind() {
4243 Some(content.chars().count())
4244 } else {
4245 None
4246 }
4247 })
4248 .unwrap_or(0);
4249 if first_id == last_id && last_len == 0 {
4250 return false;
4251 }
4252 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4253 true
4254 }
4255
4256 #[must_use]
4268 pub(crate) fn hit_test_selectable_scope(
4269 &self,
4270 anchor_or_hit: NodeId,
4271 pos: Point,
4272 ) -> Option<(NodeId, usize)> {
4273 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_or_hit);
4274 if nodes.is_empty() {
4275 return None;
4276 }
4277 let mut rects: Vec<(NodeId, Rect, TextStyle, usize)> = Vec::with_capacity(nodes.len());
4278 let mut overall_min_y: f32 = f32::INFINITY;
4279 let mut overall_max_y: f32 = f32::NEG_INFINITY;
4280 for &nid in nodes.iter() {
4281 let Some(node) = self.get_node(nid) else {
4282 continue;
4283 };
4284 let NodeKind::Text(content) = node.get_kind() else {
4285 continue;
4286 };
4287 let Some(rect) = self.text_node_screen_content_rect(nid) else {
4288 continue;
4289 };
4290 let tstyle: TextStyle = node.get_style().get_text();
4291 if pos.get_x() >= rect.get_x()
4292 && pos.get_x() <= rect.right()
4293 && pos.get_y() >= rect.get_y()
4294 && pos.get_y() <= rect.bottom()
4295 {
4296 let ch: usize = hit_test_text_char(content.as_str(), tstyle, rect, pos);
4297 return Some((nid, ch));
4298 }
4299 if rect.get_y() < overall_min_y {
4300 overall_min_y = rect.get_y();
4301 }
4302 if rect.bottom() > overall_max_y {
4303 overall_max_y = rect.bottom();
4304 }
4305 rects.push((nid, rect, tstyle, content.chars().count()));
4306 }
4307 if rects.is_empty() {
4308 return None;
4309 }
4310 if pos.get_y() < overall_min_y - 4.0 {
4311 return Some((rects[0].0, 0));
4312 }
4313 if pos.get_y() > overall_max_y + 4.0 {
4314 let last: (NodeId, Rect, TextStyle, usize) = rects[rects.len() - 1];
4315 return Some((last.0, last.3));
4316 }
4317 let mut min_dy: f32 = f32::INFINITY;
4318 for &(_, rect, _, _) in rects.iter() {
4319 let dy: f32 = if pos.get_y() < rect.get_y() {
4320 rect.get_y() - pos.get_y()
4321 } else if pos.get_y() > rect.bottom() {
4322 pos.get_y() - rect.bottom()
4323 } else {
4324 0.0
4325 };
4326 if dy < min_dy {
4327 min_dy = dy;
4328 }
4329 }
4330 let mut best: Option<(NodeId, Rect, TextStyle, f32, f32)> = None;
4331 for &(nid, rect, tstyle, _) in rects.iter() {
4332 let dy: f32 = if pos.get_y() < rect.get_y() {
4333 rect.get_y() - pos.get_y()
4334 } else if pos.get_y() > rect.bottom() {
4335 pos.get_y() - rect.bottom()
4336 } else {
4337 0.0
4338 };
4339 if dy > min_dy + 2.0 {
4340 continue;
4341 }
4342 let dx: f32 = if pos.get_x() < rect.get_x() {
4343 rect.get_x() - pos.get_x()
4344 } else if pos.get_x() > rect.right() {
4345 pos.get_x() - rect.right()
4346 } else {
4347 0.0
4348 };
4349 let better: bool = match best {
4350 None => true,
4351 Some((_, _, _, b_dx, b_dy)) => dx < b_dx || (dx == b_dx && dy < b_dy),
4352 };
4353 if better {
4354 best = Some((nid, rect, tstyle, dx, dy));
4355 }
4356 }
4357 let (best_nid, best_rect, best_style, _, _): (NodeId, Rect, TextStyle, f32, f32) = best?;
4358 let best_node: &SceneNode = self.get_node(best_nid)?;
4359 let NodeKind::Text(content) = best_node.get_kind() else {
4360 return None;
4361 };
4362 let min_y: f32 = best_rect.get_y() + 0.5;
4363 let max_y: f32 = (best_rect.bottom() - 0.5).max(min_y);
4364 let clamped_y: f32 = pos.get_y().clamp(min_y, max_y);
4365 let ch: usize = hit_test_text_char(
4366 content.as_str(),
4367 best_style,
4368 best_rect,
4369 Point::new(pos.get_x(), clamped_y),
4370 );
4371 Some((best_nid, ch))
4372 }
4373}
4374
4375impl SceneBorrowGuard {
4377 #[inline(always)]
4383 pub(crate) fn enter() -> Self {
4384 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4385 depth.set(depth.get().saturating_add(1));
4386 });
4387 Self
4388 }
4389}
4390
4391impl Drop for SceneBorrowGuard {
4393 #[inline(always)]
4399 fn drop(&mut self) {
4400 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4401 depth.set(depth.get().saturating_sub(1));
4402 });
4403 }
4404}
4405
4406impl SceneHandle {
4408 #[must_use]
4414 pub fn new_tree() -> Self {
4415 Self {
4416 inner: Rc::new(SceneHandleInner {
4417 tree: RefCell::new(SceneTree::default()),
4418 has_deferred: Cell::new(false),
4419 deferred_writes: RefCell::new(Vec::new()),
4420 }),
4421 }
4422 }
4423
4424 #[must_use]
4434 #[inline(always)]
4435 pub fn has_deferred_writes(&self) -> bool {
4436 let Self { inner } = self;
4437 inner.has_deferred.get()
4438 }
4439
4440 fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
4451 let mut executed: usize = 0;
4452 for _ in 0..MAX_FLUSH_ITERATIONS {
4453 let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
4454 Ok(mut queue) => {
4455 inner.has_deferred.set(false);
4456 if queue.is_empty() {
4457 break;
4458 }
4459 take(&mut *queue)
4460 }
4461 Err(_) => break,
4462 };
4463 for op in batch.into_iter() {
4464 op(tree);
4465 executed = executed.saturating_add(1);
4466 }
4467 if !inner.has_deferred.get() {
4468 break;
4469 }
4470 }
4471 executed
4472 }
4473
4474 pub fn flush_deferred_writes(&self) -> usize {
4484 let Self { inner } = self;
4485 if !inner.has_deferred.get() {
4486 return 0;
4487 }
4488 let executed: usize = match inner.tree.try_borrow_mut() {
4489 Ok(mut guard) => {
4490 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4491 Self::drain_deferred_locked(inner, &mut guard)
4492 }
4493 Err(_) => return 0,
4494 };
4495 if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
4496 self.flush_after_outer_borrow();
4497 }
4498 executed
4499 }
4500
4501 #[inline(always)]
4507 fn finish_outer_borrow(&self) {
4508 if is_scene_borrowed() || panicking() {
4509 return;
4510 }
4511 let Self { inner } = self;
4512 if !inner.has_deferred.get() && !has_deferred_effect_flush() {
4513 return;
4514 }
4515 self.flush_after_outer_borrow();
4516 }
4517
4518 #[cold]
4524 fn flush_after_outer_borrow(&self) {
4525 let Self { inner } = self;
4526 for _ in 0..MAX_FLUSH_ITERATIONS {
4527 let drained_writes: usize = if inner.has_deferred.get() {
4528 match inner.tree.try_borrow_mut() {
4529 Ok(mut guard) => {
4530 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4531 Self::drain_deferred_locked(inner, &mut guard)
4532 }
4533 Err(_) => 0,
4534 }
4535 } else {
4536 0
4537 };
4538 let flushed_effects: bool = if take_deferred_effect_flush() {
4539 flush_effects();
4540 true
4541 } else {
4542 false
4543 };
4544 if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
4545 break;
4546 }
4547 }
4548 }
4549
4550 pub fn mutate<CallbackFn>(&self, operation: CallbackFn)
4557 where
4558 CallbackFn: FnOnce(&mut SceneTree) + 'static,
4559 {
4560 let ran_inline: bool = {
4561 let Self { inner } = self;
4562 match inner.tree.try_borrow_mut() {
4563 Ok(mut guard) => {
4564 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4565 operation(&mut guard);
4566 if inner.has_deferred.get() {
4567 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4568 }
4569 true
4570 }
4571 Err(_) => {
4572 if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
4573 queue.push(Box::new(operation));
4574 inner.has_deferred.set(true);
4575 }
4576 notify_frame_needed();
4577 false
4578 }
4579 }
4580 };
4581 if ran_inline {
4582 self.finish_outer_borrow();
4583 }
4584 }
4585
4586 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
4595 self.mutate(move |tree: &mut SceneTree| {
4596 tree.set_virtual_scroll(id, scroll_y, content_height);
4597 });
4598 }
4599
4600 #[must_use]
4611 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
4612 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
4613 }
4614
4615 pub fn start_transition(&self, transition: NodeTransition) {
4622 self.mutate(move |tree: &mut SceneTree| {
4623 tree.start_transition(transition);
4624 });
4625 }
4626
4627 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
4635 self.mutate(move |tree: &mut SceneTree| {
4636 tree.mark_dirty(id, mask);
4637 });
4638 }
4639
4640 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
4648 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4649 |tree: &mut SceneTree| {
4650 if tree.get_node(parent).is_none() {
4651 return (Vec::new(), Vec::new());
4652 }
4653 let parent_idx: usize = parent.as_usize();
4654 let old_children: Vec<NodeId> = tree.children_vec(parent);
4655 tree.unlink_all_children_at(parent_idx);
4656 let mut all_scopes: Vec<Scope> = Vec::new();
4657 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
4658 if new_children.is_empty() {
4659 for old_child in old_children.into_iter() {
4660 let (scale_factor, ob): DisposedSubtreePayload =
4661 tree.dispose_subtree_collect(old_child);
4662 all_scopes.extend(scale_factor);
4663 all_obs.extend(ob);
4664 }
4665 } else if old_children.len() > 16 && new_children.len() > 16 {
4666 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
4667 for old_child in old_children.into_iter() {
4668 if !keep_set.contains(&old_child) {
4669 let (dpi_scale, ob): DisposedSubtreePayload =
4670 tree.dispose_subtree_collect(old_child);
4671 all_scopes.extend(dpi_scale);
4672 all_obs.extend(ob);
4673 }
4674 }
4675 } else {
4676 for old_child in old_children.into_iter() {
4677 if !new_children.contains(&old_child) {
4678 let (scroll_val, ob): DisposedSubtreePayload =
4679 tree.dispose_subtree_collect(old_child);
4680 all_scopes.extend(scroll_val);
4681 all_obs.extend(ob);
4682 }
4683 }
4684 }
4685 for child in new_children.into_iter() {
4686 if child == parent || tree.get_node(child).is_none() {
4687 continue;
4688 }
4689 let child_idx: usize = child.as_usize();
4690 let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
4691 if prev_parent != NODE_INDEX_NONE {
4692 tree.unlink_child_at(prev_parent as usize, child_idx);
4693 }
4694 tree.link_child_tail_at(parent_idx, parent, child_idx);
4695 }
4696 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4697 (all_scopes, all_obs)
4698 },
4699 (Vec::new(), Vec::new()),
4700 );
4701 finalize_disposed_subtree(scopes, observers);
4702 }
4703
4704 pub fn dismiss_portal_immediate(&self, portal: NodeId) {
4711 self.replace_children_safe(portal, Vec::new());
4712 self.with_write(
4713 |tree: &mut SceneTree| {
4714 tree.cancel_subtree_transitions(portal);
4715 tree.clear_subtree_hover(portal);
4716 if let Some(node) = tree.get_node_mut(portal) {
4717 let computed_style: &mut Style = node.get_mut_style();
4718 computed_style.get_mut_layout().set_display(Display::None);
4719 computed_style
4720 .get_mut_paint()
4721 .set_pointer_events(PointerEvents::None)
4722 .set_opacity(0.0);
4723 }
4724 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4725 tree.mark_dirty(portal, dirty_l | DIRTY_PAINT);
4726 tree.set_full_damage_pending(true);
4727 tree.clear_dirty_paint_queue();
4728 },
4729 (),
4730 );
4731 notify_frame_needed();
4732 }
4733
4734 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
4742 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4743 |tree: &mut SceneTree| {
4744 if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
4745 tree.unlink_child_at(parent.as_usize(), child.as_usize());
4746 }
4747 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
4748 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4749 out
4750 },
4751 (Vec::new(), Vec::new()),
4752 );
4753 finalize_disposed_subtree(scopes, observers);
4754 }
4755
4756 pub fn mutate_style<CallbackFn>(&self, id: NodeId, mutator: CallbackFn) -> bool
4768 where
4769 CallbackFn: FnOnce(&mut Style),
4770 {
4771 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
4772 }
4773
4774 pub fn freeze_subtree(&self, root: NodeId) {
4781 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4782 |tree: &mut SceneTree| {
4783 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4784 tree.cancel_subtree_transitions(root);
4785 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
4786 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4787 if layout.get_display() == Display::None {
4788 false
4789 } else {
4790 layout.set_display(Display::None);
4791 true
4792 }
4793 } else {
4794 false
4795 };
4796 if changed {
4797 tree.clear_subtree_hover(root);
4798 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4799 }
4800 obs
4801 },
4802 Vec::new(),
4803 );
4804 dispatch_lifecycle_freeze(&observers);
4805 }
4806
4807 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
4815 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4816 |tree: &mut SceneTree| {
4817 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4818 tree.cancel_subtree_transitions(root);
4819 let mut demoted_fixed: bool = false;
4820 let mut prev_z: i32 = 0;
4821 if let Some(node) = tree.get_node_mut(root) {
4822 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
4823 let computed_style: &mut Style = node.get_mut_style();
4824 prev_z = computed_style.layout_ref().get_z_index();
4825 demoted_fixed =
4826 !is_portal && computed_style.layout_ref().get_position() == Position::Fixed;
4827 computed_style
4828 .get_mut_layout()
4829 .set_position(Position::Absolute)
4830 .set_top(Some(0.0))
4831 .set_right(Some(0.0))
4832 .set_bottom(None)
4833 .set_left(Some(0.0))
4834 .set_z_index(0);
4835 computed_style
4836 .get_mut_paint()
4837 .set_pointer_events(PointerEvents::None);
4838 }
4839 if prev_z != 0 {
4840 let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
4841 if parent_idx != NODE_INDEX_NONE {
4842 tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
4843 }
4844 }
4845 tree.clear_subtree_hover(root);
4846 if demoted_fixed {
4847 tree.sync_portal_registration(root, false);
4848 }
4849 tree.start_transition(exit_transition.with_hide_on_complete(true));
4850 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4851 obs
4852 },
4853 Vec::new(),
4854 );
4855 dispatch_lifecycle_freeze(&observers);
4856 }
4857
4858 pub fn resume_subtree(&self, root: NodeId) {
4865 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4866 |tree: &mut SceneTree| {
4867 let mut unhidden: bool = false;
4868 if let Some(node) = tree.get_node_mut(root) {
4869 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4870 if layout.get_display() == Display::None {
4871 layout.set_display(Display::Flex);
4872 unhidden = true;
4873 }
4874 }
4875 if unhidden {
4876 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4877 } else {
4878 tree.mark_dirty(root, DIRTY_PAINT);
4879 }
4880 tree.collect_subtree_lifecycles(root)
4881 },
4882 Vec::new(),
4883 );
4884 dispatch_lifecycle_resume(&observers);
4885 }
4886
4887 pub fn activate_subtree(&self, root: NodeId) {
4894 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4895 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4896 Vec::new(),
4897 );
4898 dispatch_lifecycle_activate(&observers);
4899 }
4900
4901 pub fn update_subtree(&self, root: NodeId) {
4908 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4909 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4910 Vec::new(),
4911 );
4912 dispatch_lifecycle_update(&observers);
4913 }
4914
4915 pub fn emit_subtree_appear(&self, root: NodeId) {
4922 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4923 |tree: &SceneTree| {
4924 (
4925 tree.collect_subtree_lifecycles(root),
4926 tree.collect_subtree_scope_ids(root),
4927 )
4928 },
4929 (Vec::new(), Vec::new()),
4930 );
4931 let system_event: SystemEvent = SystemEvent::Appear;
4932 dispatch_lifecycle_system_event(&observers, &system_event);
4933 dispatch_system_event_to_scopes(&scopes, &system_event);
4934 }
4935
4936 pub fn emit_subtree_disappear(&self, root: NodeId) {
4943 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4944 |tree: &SceneTree| {
4945 (
4946 tree.collect_subtree_lifecycles(root),
4947 tree.collect_subtree_scope_ids(root),
4948 )
4949 },
4950 (Vec::new(), Vec::new()),
4951 );
4952 let system_event: SystemEvent = SystemEvent::Disappear;
4953 dispatch_lifecycle_system_event(&observers, &system_event);
4954 dispatch_system_event_to_scopes(&scopes, &system_event);
4955 }
4956
4957 #[must_use]
4967 pub fn has_active_transitions(&self) -> bool {
4968 self.with_read(SceneTree::has_active_transitions, false)
4969 }
4970
4971 #[must_use]
4981 pub fn get_selected_text(&self) -> Option<String> {
4982 self.with_read(SceneTree::get_selected_text, None)
4983 }
4984
4985 #[must_use]
4996 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4997 self.with_read(
4998 |tree: &SceneTree| tree.get_selected_text_within(container),
4999 None,
5000 )
5001 }
5002
5003 pub fn clear_text_selection(&self) {
5009 self.mutate(SceneTree::clear_text_selection);
5010 }
5011
5012 pub fn with_read<CallbackFn, ReturnValue>(
5024 &self,
5025 operation: CallbackFn,
5026 fallback: ReturnValue,
5027 ) -> ReturnValue
5028 where
5029 CallbackFn: FnOnce(&SceneTree) -> ReturnValue,
5030 {
5031 let result: ReturnValue = {
5032 let Self { inner } = self;
5033 match inner.tree.try_borrow() {
5034 Ok(guard) => {
5035 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5036 operation(&guard)
5037 }
5038 Err(_) => return fallback,
5039 }
5040 };
5041 self.finish_outer_borrow();
5042 result
5043 }
5044
5045 pub fn with_write<CallbackFn, ReturnValue>(
5057 &self,
5058 operation: CallbackFn,
5059 fallback: ReturnValue,
5060 ) -> ReturnValue
5061 where
5062 CallbackFn: FnOnce(&mut SceneTree) -> ReturnValue,
5063 {
5064 let result: ReturnValue = {
5065 let Self { inner } = self;
5066 match inner.tree.try_borrow_mut() {
5067 Ok(mut guard) => {
5068 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5069 let out: ReturnValue = operation(&mut guard);
5070 if inner.has_deferred.get() {
5071 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
5072 }
5073 out
5074 }
5075 Err(_) => return fallback,
5076 }
5077 };
5078 self.finish_outer_borrow();
5079 result
5080 }
5081
5082 pub fn bind_text<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5094 where
5095 CallbackFn: FnMut() -> String + 'static,
5096 {
5097 let handle: Self = self.clone();
5098 Effect::new(move || {
5099 let value: String = producer();
5100 handle.mutate(move |tree: &mut SceneTree| {
5101 tree.set_text(node_id, value);
5102 });
5103 })
5104 }
5105
5106 pub fn bind_style<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5118 where
5119 CallbackFn: FnMut() -> Style + 'static,
5120 {
5121 let handle: Self = self.clone();
5122 Effect::new(move || {
5123 let style: Style = producer();
5124 handle.mutate(move |tree: &mut SceneTree| {
5125 tree.set_style(node_id, style);
5126 });
5127 })
5128 }
5129}
5130
5131impl Drop for ContextShared {
5133 fn drop(&mut self) {
5139 let Self {
5140 owned_signals,
5141 runtime_epoch,
5142 ..
5143 } = self;
5144 if *runtime_epoch != current_runtime_epoch() {
5145 return;
5146 }
5147 for sig_id in owned_signals.iter().copied() {
5148 let dropped: SignalSlot = with_runtime(
5149 |runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_signal(sig_id),
5150 SignalSlot::empty(),
5151 );
5152 drop(dropped);
5153 }
5154 }
5155}
5156
5157impl Context {
5159 #[must_use]
5170 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
5171 let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
5172 let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
5173 let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
5174 let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
5175 let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
5176 let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
5177 let system_back: Signal<u64> = Signal::new_detached(0);
5178 let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
5179 let live_fps: Signal<f32> = Signal::new_detached(60.0);
5180 let present_fps: Signal<f32> = Signal::new_detached(0.0);
5181 let is_idle: Signal<bool> = Signal::new_detached(true);
5182 let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
5183 let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
5184 let exit_requested: Signal<bool> = Signal::new_detached(false);
5185 let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
5186 let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
5187 let keyboard_visible: Signal<bool> = Signal::new_detached(false);
5188 let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
5189 let orientation: Signal<ScreenOrientation> =
5190 Signal::new_detached(ScreenOrientation::Landscape);
5191 let low_power_mode: Signal<bool> = Signal::new_detached(false);
5192 let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
5193 let window_focused: Signal<bool> = Signal::new_detached(true);
5194 let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
5195 let device_motion: Signal<DeviceMotionSample> =
5196 Signal::new_detached(DeviceMotionSample::default());
5197 let owned_signals: [SignalId; 24] = [
5198 breakpoint.id(),
5199 viewport_size.id(),
5200 theme_mode.id(),
5201 safe_area.id(),
5202 gesture.id(),
5203 swipe_drag_offset.id(),
5204 system_back.id(),
5205 fps_limit.id(),
5206 live_fps.id(),
5207 present_fps.id(),
5208 is_idle.id(),
5209 display_refresh_rate.id(),
5210 active_touches.id(),
5211 exit_requested.id(),
5212 app_state.id(),
5213 network_status.id(),
5214 keyboard_visible.id(),
5215 keyboard_height.id(),
5216 orientation.id(),
5217 low_power_mode.id(),
5218 locale.id(),
5219 window_focused.id(),
5220 immersive_fullscreen.id(),
5221 device_motion.id(),
5222 ];
5223 Self {
5224 scene,
5225 breakpoint,
5226 viewport_size,
5227 theme_mode,
5228 platform,
5229 safe_area,
5230 gesture,
5231 swipe_drag_offset,
5232 system_back,
5233 dynamic_hub: DynamicUpdateHub::new(),
5234 fps_limit,
5235 live_fps,
5236 present_fps,
5237 is_idle,
5238 display_refresh_rate,
5239 active_touches,
5240 exit_requested,
5241 app_state,
5242 network_status,
5243 keyboard_visible,
5244 keyboard_height,
5245 orientation,
5246 low_power_mode,
5247 locale,
5248 window_focused,
5249 immersive_fullscreen,
5250 device_motion,
5251 shared: Rc::new(ContextShared {
5252 fullscreen_depth: Cell::new(0),
5253 clock_ms: Cell::new(0),
5254 owned_signals,
5255 runtime_epoch: current_runtime_epoch(),
5256 }),
5257 }
5258 }
5259
5260 #[must_use]
5270 pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
5271 self.get_safe_area()
5272 }
5273
5274 #[must_use]
5284 pub fn safe_area(&self) -> SafeAreaInsets {
5285 self.get_safe_area().get()
5286 }
5287
5288 #[must_use]
5298 pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
5299 self.get_immersive_fullscreen()
5300 }
5301
5302 #[must_use]
5312 pub fn is_immersive_fullscreen(&self) -> bool {
5313 self.get_immersive_fullscreen().get()
5314 }
5315
5316 pub fn set_immersive_fullscreen(&self, enabled: bool) {
5323 let Self { shared, .. } = self;
5324 let changed: bool = if enabled {
5325 if shared.fullscreen_depth.get() == 0 {
5326 shared.fullscreen_depth.set(1);
5327 }
5328 self.get_immersive_fullscreen().set_if_changed(true)
5329 } else {
5330 shared.fullscreen_depth.set(0);
5331 self.get_immersive_fullscreen().set_if_changed(false)
5332 };
5333 if changed {
5334 notify_frame_needed();
5335 }
5336 }
5337
5338 pub fn enter_immersive_fullscreen(&self) {
5344 let Self { shared, .. } = self;
5345 let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
5346 shared.fullscreen_depth.set(next);
5347 if self.get_immersive_fullscreen().set_if_changed(true) {
5348 notify_frame_needed();
5349 }
5350 }
5351
5352 pub fn exit_immersive_fullscreen(&self) {
5358 let Self { shared, .. } = self;
5359 let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
5360 shared.fullscreen_depth.set(next);
5361 if next == 0 && self.get_immersive_fullscreen().set_if_changed(false) {
5362 notify_frame_needed();
5363 }
5364 }
5365
5366 #[must_use]
5376 pub fn app_state_signal(&self) -> Signal<AppState> {
5377 self.get_app_state()
5378 }
5379
5380 pub fn emit_page_appear(&self) {
5386 let system_event: SystemEvent = SystemEvent::Appear;
5387 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5388 .get_scene()
5389 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5390 dispatch_lifecycle_system_event(&observers, &system_event);
5391 dispatch_system_event_listeners(&system_event);
5392 }
5393
5394 pub fn emit_page_disappear(&self) {
5400 let system_event: SystemEvent = SystemEvent::Disappear;
5401 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5402 .get_scene()
5403 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5404 dispatch_lifecycle_system_event(&observers, &system_event);
5405 dispatch_system_event_listeners(&system_event);
5406 }
5407
5408 pub fn emit_subtree_appear(&self, root: NodeId) {
5415 self.get_scene().emit_subtree_appear(root);
5416 }
5417
5418 pub fn emit_subtree_disappear(&self, root: NodeId) {
5425 self.get_scene().emit_subtree_disappear(root);
5426 }
5427
5428 #[must_use]
5438 pub fn elapsed_ms(&self) -> u64 {
5439 let Self { shared, .. } = self;
5440 shared.clock_ms.get()
5441 }
5442
5443 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
5450 let Self { shared, .. } = self;
5451 shared
5452 .clock_ms
5453 .set(shared.clock_ms.get().saturating_add(delta_ms));
5454 }
5455
5456 pub fn request_exit(&self) {
5462 let _: bool = self.get_exit_requested().set_if_changed(true);
5463 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
5464 }
5465
5466 pub fn copy_to_clipboard(&self, text: &str) -> bool {
5477 write_system_clipboard(text)
5478 }
5479
5480 pub fn view(&mut self, style: Style) -> NodeId {
5491 self.get_scene().with_write(
5492 |tree: &mut SceneTree| tree.create_view(style),
5493 NodeId::default(),
5494 )
5495 }
5496
5497 pub fn text(&mut self, content: String, style: Style) -> NodeId {
5509 self.get_scene().with_write(
5510 |tree: &mut SceneTree| tree.create_text(content, style),
5511 NodeId::default(),
5512 )
5513 }
5514
5515 pub fn reactive_text<CallbackFn>(&mut self, style: Style, producer: CallbackFn) -> NodeId
5527 where
5528 CallbackFn: FnMut() -> String + 'static,
5529 {
5530 let node_id: NodeId = self.text(String::new(), style);
5531 let handle: SceneHandle = self.get_scene().clone();
5532 let (scope, _): (Scope, Effect) =
5533 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
5534 self.get_scene().with_write(
5535 |tree: &mut SceneTree| {
5536 tree.attach_scope(node_id, scope);
5537 },
5538 (),
5539 );
5540 node_id
5541 }
5542
5543 pub fn scroll_view(&mut self, style: Style) -> NodeId {
5554 self.get_scene().with_write(
5555 |tree: &mut SceneTree| tree.create_scroll_view(style),
5556 NodeId::default(),
5557 )
5558 }
5559
5560 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
5572 self.get_scene().with_write(
5573 |tree: &mut SceneTree| tree.create_input(state, style),
5574 NodeId::default(),
5575 )
5576 }
5577
5578 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
5590 self.get_scene().with_write(
5591 |tree: &mut SceneTree| tree.create_image(buffer, style),
5592 NodeId::default(),
5593 )
5594 }
5595
5596 pub fn canvas<CallbackFn>(&mut self, style: Style, painter: CallbackFn) -> NodeId
5608 where
5609 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5610 {
5611 self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
5612 }
5613
5614 pub fn canvas_with_caching<CallbackFn>(
5627 &mut self,
5628 style: Style,
5629 caching: CanvasCaching,
5630 painter: CallbackFn,
5631 ) -> NodeId
5632 where
5633 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5634 {
5635 let callback_fn: CanvasDrawCallback = Rc::new(RefCell::new(painter));
5636 self.get_scene().with_write(
5637 |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, callback_fn),
5638 NodeId::default(),
5639 )
5640 }
5641
5642 pub fn portal(&mut self, style: Style) -> NodeId {
5653 self.get_scene().with_write(
5654 |tree: &mut SceneTree| tree.create_portal(style),
5655 NodeId::default(),
5656 )
5657 }
5658
5659 pub fn fragment(&mut self) -> NodeId {
5669 self.get_scene().with_write(
5670 |tree: &mut SceneTree| tree.create_fragment(),
5671 NodeId::default(),
5672 )
5673 }
5674
5675 pub fn append(&mut self, parent: NodeId, child: NodeId) {
5683 self.get_scene().with_write(
5684 |tree: &mut SceneTree| {
5685 tree.append_child(parent, child);
5686 },
5687 (),
5688 );
5689 }
5690
5691 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
5699 if children.is_empty() {
5700 return;
5701 }
5702 self.get_scene().with_write(
5703 |tree: &mut SceneTree| {
5704 tree.append_children(parent, children);
5705 },
5706 (),
5707 );
5708 }
5709
5710 pub fn bind_style<CallbackFn>(&mut self, node_id: NodeId, producer: CallbackFn)
5718 where
5719 CallbackFn: FnMut() -> Style + 'static,
5720 {
5721 let handle: SceneHandle = self.get_scene().clone();
5722 let (scope, _): (Scope, Effect) =
5723 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
5724 self.get_scene().with_write(
5725 |tree: &mut SceneTree| {
5726 tree.attach_scope(node_id, scope);
5727 },
5728 (),
5729 );
5730 }
5731
5732 pub fn on_pointer_enter<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5740 where
5741 CallbackFn: FnMut(&UiEvent) + 'static,
5742 {
5743 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5744 self.get_scene().with_write(
5745 |tree: &mut SceneTree| {
5746 if let Some(node) = tree.get_node_mut(node_id) {
5747 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5748 }
5749 },
5750 (),
5751 );
5752 }
5753
5754 pub fn on_pointer_leave<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5762 where
5763 CallbackFn: FnMut(&UiEvent) + 'static,
5764 {
5765 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5766 self.get_scene().with_write(
5767 |tree: &mut SceneTree| {
5768 if let Some(node) = tree.get_node_mut(node_id) {
5769 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
5770 }
5771 },
5772 (),
5773 );
5774 }
5775
5776 pub fn on_focus<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5784 where
5785 CallbackFn: FnMut(&UiEvent) + 'static,
5786 {
5787 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5788 self.get_scene().with_write(
5789 |tree: &mut SceneTree| {
5790 if let Some(node) = tree.get_node_mut(node_id) {
5791 node.get_mut_handlers().set_on_focus(Some(handler));
5792 node.get_mut_interaction().set_focusable(true);
5793 }
5794 },
5795 (),
5796 );
5797 }
5798
5799 pub fn on_blur<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5807 where
5808 CallbackFn: FnMut(&UiEvent) + 'static,
5809 {
5810 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5811 self.get_scene().with_write(
5812 |tree: &mut SceneTree| {
5813 if let Some(node) = tree.get_node_mut(node_id) {
5814 node.get_mut_handlers().set_on_blur(Some(handler));
5815 }
5816 },
5817 (),
5818 );
5819 }
5820
5821 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
5829 self.get_scene().with_write(
5830 |tree: &mut SceneTree| {
5831 if let Some(node) = tree.get_node_mut(node_id) {
5832 node.get_mut_interaction().set_focusable(focusable);
5833 }
5834 },
5835 (),
5836 );
5837 }
5838
5839 pub fn on_click<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5847 where
5848 CallbackFn: FnMut(&UiEvent) + 'static,
5849 {
5850 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5851 self.get_scene().with_write(
5852 |tree: &mut SceneTree| {
5853 if let Some(node) = tree.get_node_mut(node_id) {
5854 node.get_mut_handlers().set_on_click(Some(handler));
5855 node.get_mut_interaction().set_focusable(true);
5856 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5857 if paint.get_cursor() == CursorIcon::Default {
5858 paint.set_cursor(CursorIcon::Pointer);
5859 }
5860 }
5861 },
5862 (),
5863 );
5864 }
5865
5866 pub fn on_change<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5874 where
5875 CallbackFn: FnMut(&UiEvent) + 'static,
5876 {
5877 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5878 self.get_scene().with_write(
5879 |tree: &mut SceneTree| {
5880 if let Some(node) = tree.get_node_mut(node_id) {
5881 node.get_mut_handlers().set_on_change(Some(handler));
5882 }
5883 },
5884 (),
5885 );
5886 }
5887
5888 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
5896 self.get_scene().with_write(
5897 |tree: &mut SceneTree| {
5898 if let Some(node) = tree.get_node_mut(node_id) {
5899 node.set_a11y(Some(props));
5900 }
5901 },
5902 (),
5903 );
5904 }
5905
5906 pub fn on_scroll<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5914 where
5915 CallbackFn: FnMut(&UiEvent) + 'static,
5916 {
5917 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5918 self.get_scene().with_write(
5919 |tree: &mut SceneTree| {
5920 if let Some(node) = tree.get_node_mut(node_id) {
5921 node.get_mut_handlers().set_on_scroll(Some(handler));
5922 }
5923 },
5924 (),
5925 );
5926 }
5927
5928 pub fn on_pointer_down<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5936 where
5937 CallbackFn: FnMut(&UiEvent) + 'static,
5938 {
5939 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5940 self.get_scene().with_write(
5941 |tree: &mut SceneTree| {
5942 if let Some(node) = tree.get_node_mut(node_id) {
5943 node.get_mut_handlers().set_on_pointer_down(Some(handler));
5944 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5945 if paint.get_cursor() == CursorIcon::Default {
5946 paint.set_cursor(CursorIcon::Pointer);
5947 }
5948 }
5949 },
5950 (),
5951 );
5952 }
5953
5954 pub fn on_pointer_move<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5962 where
5963 CallbackFn: FnMut(&UiEvent) + 'static,
5964 {
5965 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5966 self.get_scene().with_write(
5967 |tree: &mut SceneTree| {
5968 if let Some(node) = tree.get_node_mut(node_id) {
5969 node.get_mut_handlers().set_on_pointer_move(Some(handler));
5970 }
5971 },
5972 (),
5973 );
5974 }
5975
5976 pub fn on_pointer_up<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5984 where
5985 CallbackFn: FnMut(&UiEvent) + 'static,
5986 {
5987 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5988 self.get_scene().with_write(
5989 |tree: &mut SceneTree| {
5990 if let Some(node) = tree.get_node_mut(node_id) {
5991 node.get_mut_handlers().set_on_pointer_up(Some(handler));
5992 }
5993 },
5994 (),
5995 );
5996 }
5997
5998 pub fn on_pointer_cancel<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6006 where
6007 CallbackFn: FnMut(&UiEvent) + 'static,
6008 {
6009 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6010 self.get_scene().with_write(
6011 |tree: &mut SceneTree| {
6012 if let Some(node) = tree.get_node_mut(node_id) {
6013 node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
6014 }
6015 },
6016 (),
6017 );
6018 }
6019
6020 pub fn on_hover<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6028 where
6029 CallbackFn: FnMut(&UiEvent) + 'static,
6030 {
6031 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6032 let leave_handler: UiEventHandler = handler.clone();
6033 self.get_scene().with_write(
6034 |tree: &mut SceneTree| {
6035 if let Some(node) = tree.get_node_mut(node_id) {
6036 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
6037 node.get_mut_handlers()
6038 .set_on_pointer_leave(Some(leave_handler));
6039 }
6040 },
6041 (),
6042 );
6043 }
6044
6045 pub fn on_key<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6053 where
6054 CallbackFn: FnMut(&UiEvent) + 'static,
6055 {
6056 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6057 self.get_scene().with_write(
6058 |tree: &mut SceneTree| {
6059 if let Some(node) = tree.get_node_mut(node_id) {
6060 node.get_mut_handlers().set_on_key_down(Some(handler));
6061 node.get_mut_interaction().set_focusable(true);
6062 }
6063 },
6064 (),
6065 );
6066 }
6067
6068 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
6077 self.get_scene()
6078 .set_virtual_scroll(node_id, scroll_y, content_height);
6079 }
6080
6081 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
6089 self.get_scene().with_write(
6090 |tree: &mut SceneTree| {
6091 tree.set_scroll_offset(node_id, offset);
6092 },
6093 (),
6094 );
6095 }
6096
6097 pub fn start_transition(&mut self, transition: NodeTransition) {
6104 self.get_scene().start_transition(transition);
6105 }
6106
6107 pub fn bind_children<CallbackFn>(&mut self, host: NodeId, mut builder: CallbackFn)
6115 where
6116 CallbackFn: FnMut() -> Vec<NodeId> + 'static,
6117 {
6118 let ctx_clone: Self = self.clone();
6119 let handle: SceneHandle = self.get_scene().clone();
6120 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6121 Effect::new(move || {
6122 let (child_scope, children): (Scope, Vec<NodeId>) =
6123 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
6124 let first_opt: Option<NodeId> = children.first().copied();
6125 handle.replace_children_safe(host, children);
6126 if let Some(first) = first_opt {
6127 handle.mutate(move |tree: &mut SceneTree| {
6128 tree.attach_scope(first, child_scope);
6129 });
6130 } else {
6131 child_scope.dispose();
6132 }
6133 })
6134 });
6135 self.get_scene().mutate(move |tree: &mut SceneTree| {
6136 tree.attach_scope(host, scope);
6137 });
6138 }
6139
6140 pub fn bind_children_keyed<ValueType, KeyType, Items, KeyFn, RenderFn>(
6150 &mut self,
6151 host: NodeId,
6152 mut items_fn: Items,
6153 mut key_fn: KeyFn,
6154 mut render_fn: RenderFn,
6155 ) where
6156 ValueType: 'static,
6157 KeyType: Eq + Hash + 'static,
6158 Items: FnMut() -> Vec<ValueType> + 'static,
6159 KeyFn: FnMut(&ValueType) -> KeyType + 'static,
6160 RenderFn: FnMut(ValueType) -> NodeId + 'static,
6161 {
6162 let ctx_clone: Self = self.clone();
6163 let handle: SceneHandle = self.get_scene().clone();
6164 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6165 let mut live_nodes: HashMap<KeyType, NodeId> = HashMap::new();
6166 Effect::new(move || {
6167 let next_items: Vec<ValueType> = items_fn();
6168 let mut next_map: HashMap<KeyType, NodeId> =
6169 HashMap::with_capacity(next_items.len());
6170 let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
6171 let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
6172 for item in next_items.into_iter() {
6173 let key: KeyType = key_fn(&item);
6174 if let Some(existing_id) = live_nodes.remove(&key) {
6175 next_children.push(existing_id);
6176 let _: Option<NodeId> = next_map.insert(key, existing_id);
6177 } else {
6178 let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
6179 with_context(ctx_clone.clone(), || render_fn(item))
6180 });
6181 new_scopes.push((mounted_id, item_scope));
6182 next_children.push(mounted_id);
6183 let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
6184 }
6185 }
6186 live_nodes = next_map;
6187 handle.replace_children_safe(host, next_children);
6188 if !new_scopes.is_empty() {
6189 handle.mutate(move |tree: &mut SceneTree| {
6190 for (nid, item_scope) in new_scopes.into_iter() {
6191 tree.attach_scope(nid, item_scope);
6192 }
6193 });
6194 }
6195 })
6196 });
6197 self.get_scene().mutate(move |tree: &mut SceneTree| {
6198 tree.attach_scope(host, scope);
6199 });
6200 }
6201}
6202
6203impl Drop for ContextGuard {
6205 fn drop(&mut self) {
6211 let Self { previous } = self;
6212 let restored: Option<Context> = previous.take();
6213 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
6214 *slot.borrow_mut() = restored;
6215 });
6216 }
6217}
6218
6219impl NodeRefTarget for NodeId {
6221 fn bind_node_ref(&mut self, id: NodeId) {
6228 *self = id;
6229 }
6230}
6231
6232impl NodeRefTarget for Option<NodeId> {
6234 fn bind_node_ref(&mut self, id: NodeId) {
6241 *self = Some(id);
6242 }
6243}
6244
6245impl NodeRefTarget for Cell<NodeId> {
6247 fn bind_node_ref(&mut self, id: NodeId) {
6254 self.set(id);
6255 }
6256}
6257
6258impl NodeRefTarget for Rc<Cell<NodeId>> {
6260 fn bind_node_ref(&mut self, id: NodeId) {
6267 self.set(id);
6268 }
6269}
6270
6271impl NodeRefTarget for Cell<Option<NodeId>> {
6273 fn bind_node_ref(&mut self, id: NodeId) {
6280 self.set(Some(id));
6281 }
6282}
6283
6284impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
6286 fn bind_node_ref(&mut self, id: NodeId) {
6293 self.set(Some(id));
6294 }
6295}
6296
6297impl TextNodeContent for String {
6299 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6311 ctx.text(self, style)
6312 }
6313
6314 fn mount_text_current(self, style: Style) -> NodeId {
6325 with_current_context(|ctx: &Context| {
6326 ctx.get_scene().with_write(
6327 |tree: &mut SceneTree| tree.create_text(self, style),
6328 NodeId::default(),
6329 )
6330 })
6331 }
6332}
6333
6334impl TextNodeContent for &str {
6336 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6348 ctx.text(self.to_string(), style)
6349 }
6350
6351 fn mount_text_current(self, style: Style) -> NodeId {
6362 let owned: String = self.to_string();
6363 with_current_context(|ctx: &Context| {
6364 ctx.get_scene().with_write(
6365 |tree: &mut SceneTree| tree.create_text(owned, style),
6366 NodeId::default(),
6367 )
6368 })
6369 }
6370}
6371
6372impl TextNodeContent for &String {
6374 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6386 ctx.text(self.clone(), style)
6387 }
6388
6389 fn mount_text_current(self, style: Style) -> NodeId {
6400 let owned: String = self.clone();
6401 with_current_context(|ctx: &Context| {
6402 ctx.get_scene().with_write(
6403 |tree: &mut SceneTree| tree.create_text(owned, style),
6404 NodeId::default(),
6405 )
6406 })
6407 }
6408}
6409
6410impl TextNodeContent for Cow<'_, str> {
6412 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6424 ctx.text(self.into_owned(), style)
6425 }
6426
6427 fn mount_text_current(self, style: Style) -> NodeId {
6438 let owned: String = self.into_owned();
6439 with_current_context(|ctx: &Context| {
6440 ctx.get_scene().with_write(
6441 |tree: &mut SceneTree| tree.create_text(owned, style),
6442 NodeId::default(),
6443 )
6444 })
6445 }
6446}
6447
6448impl<CallbackFn, TextValue> TextNodeContent for CallbackFn
6450where
6451 CallbackFn: FnMut() -> TextValue + 'static,
6452 TextValue: Into<String>,
6453{
6454 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
6466 ctx.reactive_text(style, move || self().into())
6467 }
6468
6469 fn mount_text_current(mut self, style: Style) -> NodeId {
6480 mount_reactive_text(style, move || self().into())
6481 }
6482}