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 active_webview_node: None,
144 }
145 }
146}
147
148impl SceneTree {
150 fn live_generation(&self, id: NodeId) -> Option<u32> {
161 let meta: &NodeMeta = self.get_meta().get(id.as_usize())?;
162 ((meta.get_flags() & NODE_FLAG_ALIVE) != 0 && meta.get_generation() == id.get_generation())
163 .then_some(id.get_generation())
164 }
165
166 fn theme_entry(&self, id: NodeId) -> Option<ThemeNodeEntry> {
177 let generation: u32 = self.live_generation(id)?;
178 let Self { theme_entries, .. } = self;
179 theme_entries
180 .get(&id.get_index())
181 .copied()
182 .filter(|entry: &ThemeNodeEntry| entry.get_generation() == generation)
183 }
184
185 fn update_theme_entry<CallbackFn>(&mut self, id: NodeId, apply: CallbackFn)
193 where
194 CallbackFn: FnOnce(&mut ThemeNodeEntry),
195 {
196 let Some(generation) = self.live_generation(id) else {
197 return;
198 };
199 let Self { theme_entries, .. } = self;
200 let entry: &mut ThemeNodeEntry = theme_entries
201 .entry(id.get_index())
202 .or_insert_with(|| ThemeNodeEntry::new(generation, false, None));
203 if entry.get_generation() != generation {
204 *entry = ThemeNodeEntry::new(generation, false, None);
205 }
206 apply(entry);
207 }
208
209 pub fn set_theme_owned(&mut self, id: NodeId, owned: bool) {
217 if !owned && self.theme_entry(id).is_none() {
218 return;
219 }
220 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
221 entry.set_owned(owned);
222 });
223 }
224
225 #[must_use]
236 pub fn is_theme_owned(&self, id: NodeId) -> bool {
237 self.theme_entry(id)
238 .is_some_and(|entry: ThemeNodeEntry| entry.get_owned())
239 }
240
241 #[must_use]
252 pub fn theme_baseline(&self, id: NodeId) -> Option<ThemeBaseline> {
253 self.theme_entry(id)
254 .and_then(|entry: ThemeNodeEntry| entry.get_baseline())
255 }
256
257 pub fn set_theme_baseline(&mut self, id: NodeId, baseline: Option<ThemeBaseline>) {
265 if baseline.is_none() && self.theme_entry(id).is_none() {
266 return;
267 }
268 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
269 entry.set_baseline(baseline);
270 });
271 }
272}
273
274impl SceneTree {
276 pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
284 if self.get_node(id).is_none() {
285 return;
286 }
287 let clamped: f32 = if blur_radius.is_finite() {
288 blur_radius.clamp(0.0, 96.0)
289 } else {
290 0.0
291 };
292 let prev_radius: f32 = self.backdrop_blur_radius(id);
293 if (prev_radius - clamped).abs() <= 0.001 {
294 return;
295 }
296 if prev_radius > 0.0 {
297 self.record_node_logical_damage(id);
298 }
299 let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
300 if clamped <= 0.0 {
301 blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
302 } else if let Some(slot) = blurs
303 .iter_mut()
304 .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
305 {
306 slot.1 = clamped;
307 } else {
308 blurs.push((id, clamped));
309 }
310 let paint_copy: Option<PaintStyle> =
311 self.get_node(id).map(|node: &SceneNode| *node.paint_ref());
312 if let Some(paint) = paint_copy {
313 self.sync_node_compact_paint(id.as_usize(), &paint, clamped);
314 }
315 self.mark_dirty(id, DIRTY_PAINT);
316 }
317
318 #[must_use]
329 pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
330 for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
331 if nid == id {
332 return radius;
333 }
334 }
335 0.0
336 }
337
338 #[must_use]
348 pub fn has_backdrop_blur_nodes(&self) -> bool {
349 !self.get_backdrop_blur_nodes().is_empty()
350 }
351
352 pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
364 if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
365 return 0;
366 }
367 let clamped_scale: f32 = scale.max(0.5);
368 let blur_count: usize = self.get_backdrop_blur_nodes().len();
369 let mut dirtied: Vec<bool> = vec![false; blur_count];
370 let mut total_added: usize = 0;
371 let mut changed: bool = true;
372 while changed && !damage.get_full_damage() {
373 changed = false;
374 if damage.bounds_rect().is_none() {
375 break;
376 }
377 for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
378 if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
379 continue;
380 }
381 let Some(screen_rect) = self.node_screen_bounds(nid) else {
382 continue;
383 };
384 if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
385 continue;
386 }
387 let sigma: f32 = (blur_radius * 0.5).max(0.75);
388 let halo: f32 = (sigma * 3.0).ceil() + 2.0;
389 let sample_logical: Rect = Rect::new(
390 screen_rect.get_x() - halo,
391 screen_rect.get_y() - halo,
392 screen_rect.get_width() + halo * 2.0,
393 screen_rect.get_height() + halo * 2.0,
394 );
395 let sample_phys: Rect =
396 Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
397 let output_phys: Rect = Self::scale_logical_to_phys_rect(
398 Rect::new(
399 screen_rect.get_x() - 2.0,
400 screen_rect.get_y() - 2.0,
401 screen_rect.get_width() + 4.0,
402 screen_rect.get_height() + 4.0,
403 ),
404 clamped_scale,
405 );
406 let (rects, count): ([Rect; 8], usize) =
407 damage.normalized_rects(u32::MAX, u32::MAX);
408 let overlaps: bool = rects
409 .iter()
410 .take(count)
411 .any(|rect_bounds: &Rect| rect_bounds.intersect(sample_phys).is_some());
412 if overlaps {
413 damage.add_rect(output_phys);
414 dirtied[idx] = true;
415 total_added += 1;
416 changed = true;
417 }
418 }
419 }
420 total_added
421 }
422
423 pub fn effect_dependency_damage(
439 &self,
440 dirty_set: &mut DirtyRectSet,
441 extra_portals: &[PortalBackdropRegion],
442 viewport_w: u32,
443 viewport_h: u32,
444 scale: f32,
445 full_ratio_threshold: f32,
446 ) -> EffectDamageReport {
447 if dirty_set.get_full_frame() {
448 return EffectDamageReport::new(
449 0,
450 extra_portals.len() + self.get_backdrop_blur_nodes().len(),
451 true,
452 );
453 }
454 let mut combined: Vec<PortalBackdropRegion> =
455 Vec::with_capacity(extra_portals.len() + self.get_backdrop_blur_nodes().len());
456 combined.extend_from_slice(extra_portals);
457 for &(nid, blur_radius) in self.get_backdrop_blur_nodes().iter() {
458 if blur_radius <= 0.0 || !self.is_node_visible(nid) {
459 continue;
460 }
461 if let Some(screen_rect) = self.node_screen_bounds(nid)
462 && screen_rect.get_width() > 0.0
463 && screen_rect.get_height() > 0.0
464 {
465 let is_dirty: bool = self
466 .get_node(nid)
467 .map(|scene_node: &SceneNode| scene_node.get_dirty().get_bits() != DIRTY_NONE)
468 .unwrap_or(false);
469 combined.push(PortalBackdropRegion::new(
470 screen_rect,
471 blur_radius,
472 is_dirty,
473 ));
474 }
475 }
476 dirty_set.apply_effect_dependency_damage(
477 &combined,
478 viewport_w,
479 viewport_h,
480 scale,
481 full_ratio_threshold,
482 )
483 }
484
485 #[must_use]
495 #[inline(always)]
496 pub fn portal_nodes(&self) -> &[NodeId] {
497 let Self { portal_nodes, .. } = self;
498 portal_nodes.as_slice()
499 }
500
501 #[must_use]
511 #[inline(always)]
512 pub fn has_portal_nodes(&self) -> bool {
513 let Self { portal_nodes, .. } = self;
514 !portal_nodes.is_empty()
515 }
516
517 fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
525 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
526 let next: u16 = if is_portal {
527 meta.get_flags() | NODE_FLAG_IS_PORTAL
528 } else {
529 meta.get_flags() & !NODE_FLAG_IS_PORTAL
530 };
531 let _: &mut NodeMeta = meta.set_flags(next);
532 }
533 let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
534 if is_portal {
535 if !portals.contains(&id) {
536 portals.push(id);
537 }
538 } else if !portals.is_empty() {
539 portals.retain(|existing: &NodeId| *existing != id);
540 }
541 }
542
543 #[must_use]
553 #[inline(always)]
554 pub fn scroll_nodes(&self) -> &[NodeId] {
555 let Self { scroll_nodes, .. } = self;
556 scroll_nodes.as_slice()
557 }
558
559 #[must_use]
569 #[inline(always)]
570 pub fn has_scroll_nodes(&self) -> bool {
571 let Self { scroll_nodes, .. } = self;
572 !scroll_nodes.is_empty()
573 }
574
575 fn sync_scroll_registration(&mut self, id: NodeId, is_scroll: bool) {
583 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
584 let next: u16 = if is_scroll {
585 meta.get_flags() | NODE_FLAG_IS_SCROLL_CONTAINER
586 } else {
587 meta.get_flags() & !NODE_FLAG_IS_SCROLL_CONTAINER
588 };
589 let _: &mut NodeMeta = meta.set_flags(next);
590 }
591 let scrolls: &mut Vec<NodeId> = self.get_mut_scroll_nodes();
592 if is_scroll {
593 if !scrolls.contains(&id) {
594 scrolls.push(id);
595 }
596 } else if !scrolls.is_empty() {
597 scrolls.retain(|existing: &NodeId| *existing != id);
598 }
599 }
600
601 fn sync_node_compact_paint(&mut self, idx: usize, paint: &PaintStyle, blur: f32) {
610 let prev_effect_id: u32 = self
611 .get_compact_paints()
612 .get(idx)
613 .map(CompactPaintStyle::get_effect_id)
614 .unwrap_or(EFFECT_ID_NONE);
615 let entry: PaintEffectEntry = PaintEffectEntry::from_paint_and_blur(paint, blur);
616 let next_effect_id: u32 = self.get_mut_effect_table().update(prev_effect_id, entry);
617 let compact: CompactPaintStyle = CompactPaintStyle::from_paint(paint, next_effect_id);
618 if let Some(slot) = self.get_mut_compact_paints().get_mut(idx) {
619 *slot = compact;
620 }
621 }
622
623 #[must_use]
634 #[inline(always)]
635 pub fn compact_paint(&self, id: NodeId) -> Option<&CompactPaintStyle> {
636 let idx: usize = id.as_usize();
637 let meta: &NodeMeta = self.get_meta().get(idx)?;
638 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
639 {
640 return None;
641 }
642 self.get_compact_paints().get(idx)
643 }
644
645 #[must_use]
656 #[inline(always)]
657 pub fn paint_effect(&self, id: NodeId) -> Option<&PaintEffectEntry> {
658 let effect_id: u32 = self.compact_paint(id)?.get_effect_id();
659 self.get_effect_table().get(effect_id)
660 }
661
662 #[must_use]
672 #[inline(always)]
673 pub fn effect_table(&self) -> &EffectTable {
674 self.get_effect_table()
675 }
676
677 #[must_use]
688 #[inline(always)]
689 pub fn has_extras(&self, id: NodeId) -> bool {
690 let Some(node) = self.get_node(id) else {
691 return false;
692 };
693 node.has_extras()
694 }
695
696 #[must_use]
707 #[inline(always)]
708 pub fn has_nonzero_z_child(&self, id: NodeId) -> bool {
709 let idx: usize = id.as_usize();
710 let Some(meta) = self.get_meta().get(idx) else {
711 return false;
712 };
713 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
714 && meta.get_generation() == id.get_generation()
715 && (meta.get_flags() & NODE_FLAG_HAS_NONZERO_Z_CHILD) != 0
716 }
717
718 #[must_use]
729 #[inline(always)]
730 pub fn has_lifecycle(&self, id: NodeId) -> bool {
731 let idx: usize = id.as_usize();
732 let Some(meta) = self.get_meta().get(idx) else {
733 return false;
734 };
735 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
736 && meta.get_generation() == id.get_generation()
737 && (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
738 }
739
740 #[must_use]
751 #[inline(always)]
752 pub fn has_scope(&self, id: NodeId) -> bool {
753 let idx: usize = id.as_usize();
754 let Some(meta) = self.get_meta().get(idx) else {
755 return false;
756 };
757 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
758 && meta.get_generation() == id.get_generation()
759 && (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
760 }
761
762 #[must_use]
773 #[inline(always)]
774 pub fn children_iter(&self, parent: NodeId) -> SceneChildIter<'_> {
775 let idx: usize = parent.as_usize();
776 let valid: bool = self.get_meta().get(idx).is_some_and(|meta: &NodeMeta| {
777 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
778 && meta.get_generation() == parent.get_generation()
779 });
780 if !valid {
781 return SceneChildIter {
782 meta: self.get_meta().as_slice(),
783 topology: self.get_topology().as_slice(),
784 head: NODE_INDEX_NONE,
785 tail: NODE_INDEX_NONE,
786 remaining: 0,
787 };
788 }
789 let topo: NodeTopology = self.get_topology()[idx];
790 SceneChildIter {
791 meta: self.get_meta().as_slice(),
792 topology: self.get_topology().as_slice(),
793 head: topo.get_first_child(),
794 tail: topo.get_last_child(),
795 remaining: topo.get_child_count() as usize,
796 }
797 }
798
799 #[inline]
807 pub fn for_each_child<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
808 where
809 CallbackFn: FnMut(NodeId),
810 {
811 for child_id in self.children_iter(parent) {
812 visit(child_id);
813 }
814 }
815
816 #[inline]
824 pub fn for_each_child_rev<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
825 where
826 CallbackFn: FnMut(NodeId),
827 {
828 for child_id in self.children_iter(parent).rev() {
829 visit(child_id);
830 }
831 }
832
833 #[must_use]
844 #[inline(always)]
845 pub fn child_count(&self, parent: NodeId) -> usize {
846 let idx: usize = parent.as_usize();
847 let Some(meta) = self.get_meta().get(idx) else {
848 return 0;
849 };
850 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
851 || meta.get_generation() != parent.get_generation()
852 {
853 return 0;
854 }
855 self.get_topology()[idx].get_child_count() as usize
856 }
857
858 #[must_use]
869 #[inline(always)]
870 pub fn has_children(&self, parent: NodeId) -> bool {
871 self.child_count(parent) > 0
872 }
873
874 #[must_use]
885 #[inline(always)]
886 pub fn first_child(&self, parent: NodeId) -> Option<NodeId> {
887 let idx: usize = parent.as_usize();
888 let meta: &NodeMeta = self.get_meta().get(idx)?;
889 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
890 || meta.get_generation() != parent.get_generation()
891 {
892 return None;
893 }
894 let first: u32 = self.get_topology()[idx].get_first_child();
895 if first == NODE_INDEX_NONE {
896 None
897 } else {
898 Some(NodeId::new(
899 first,
900 self.get_meta()[first as usize].get_generation(),
901 ))
902 }
903 }
904
905 #[must_use]
916 #[inline(always)]
917 pub fn last_child(&self, parent: NodeId) -> Option<NodeId> {
918 let idx: usize = parent.as_usize();
919 let meta: &NodeMeta = self.get_meta().get(idx)?;
920 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
921 || meta.get_generation() != parent.get_generation()
922 {
923 return None;
924 }
925 let last: u32 = self.get_topology()[idx].get_last_child();
926 if last == NODE_INDEX_NONE {
927 None
928 } else {
929 Some(NodeId::new(
930 last,
931 self.get_meta()[last as usize].get_generation(),
932 ))
933 }
934 }
935
936 #[must_use]
947 #[inline(always)]
948 pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
949 let idx: usize = id.as_usize();
950 let meta: &NodeMeta = self.get_meta().get(idx)?;
951 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
952 {
953 return None;
954 }
955 let next: u32 = self.get_topology()[idx].get_next_sibling();
956 if next == NODE_INDEX_NONE {
957 None
958 } else {
959 Some(NodeId::new(
960 next,
961 self.get_meta()[next as usize].get_generation(),
962 ))
963 }
964 }
965
966 #[must_use]
977 #[inline(always)]
978 pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
979 let idx: usize = id.as_usize();
980 let meta: &NodeMeta = self.get_meta().get(idx)?;
981 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
982 {
983 return None;
984 }
985 let prev: u32 = self.get_topology()[idx].get_prev_sibling();
986 if prev == NODE_INDEX_NONE {
987 None
988 } else {
989 Some(NodeId::new(
990 prev,
991 self.get_meta()[prev as usize].get_generation(),
992 ))
993 }
994 }
995
996 #[must_use]
1007 pub fn children_vec(&self, parent: NodeId) -> Vec<NodeId> {
1008 self.children_iter(parent).collect()
1009 }
1010
1011 #[must_use]
1023 pub fn is_in_subtree(&self, candidate: NodeId, root: NodeId) -> bool {
1024 if candidate == root {
1025 return true;
1026 }
1027 let mut cursor_idx: usize = candidate.as_usize();
1028 let Some(start_meta) = self.get_meta().get(cursor_idx) else {
1029 return false;
1030 };
1031 if (start_meta.get_flags() & NODE_FLAG_ALIVE) == 0
1032 || start_meta.get_generation() != candidate.get_generation()
1033 {
1034 return false;
1035 }
1036 let root_idx: u32 = root.get_index();
1037 let root_gen: u32 = root.get_generation();
1038 let max_hops: usize = self.get_topology().len();
1039 let mut hops: usize = 0;
1040 while hops < max_hops {
1041 let parent_idx: u32 = self.get_topology()[cursor_idx].get_parent();
1042 if parent_idx == NODE_INDEX_NONE {
1043 return false;
1044 }
1045 if parent_idx == root_idx
1046 && self.get_meta()[parent_idx as usize].get_generation() == root_gen
1047 {
1048 return true;
1049 }
1050 cursor_idx = parent_idx as usize;
1051 hops += 1;
1052 }
1053 false
1054 }
1055
1056 fn recompute_nonzero_z_child(&mut self, parent_idx: usize) {
1063 let mut any_nonzero: bool = false;
1064 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1065 while cur != NODE_INDEX_NONE {
1066 let ci: usize = cur as usize;
1067 if self.get_nodes()[ci].layout_ref().get_z_index() != 0 {
1068 any_nonzero = true;
1069 break;
1070 }
1071 cur = self.get_topology()[ci].get_next_sibling();
1072 }
1073 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1074 let next: u16 = if any_nonzero {
1075 meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD
1076 } else {
1077 meta.get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD
1078 };
1079 let _: &mut NodeMeta = meta.set_flags(next);
1080 }
1081 }
1082
1083 fn sync_parent_nonzero_z(&mut self, parent_idx: usize, prev_z: i32, next_z: i32) {
1092 if next_z != 0 {
1093 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1094 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1095 let _: &mut NodeMeta = meta.set_flags(next);
1096 }
1097 } else if prev_z != 0 {
1098 self.recompute_nonzero_z_child(parent_idx);
1099 }
1100 }
1101
1102 fn unlink_child_at(&mut self, parent_idx: usize, child_idx: usize) {
1110 let child_topo: NodeTopology = self.get_topology()[child_idx];
1111 if child_topo.get_parent() != parent_idx as u32 {
1112 return;
1113 }
1114 let prev: u32 = child_topo.get_prev_sibling();
1115 let next: u32 = child_topo.get_next_sibling();
1116 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1117 if prev != NODE_INDEX_NONE {
1118 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(next);
1119 } else {
1120 let _: &mut NodeTopology = topo[parent_idx].set_first_child(next);
1121 }
1122 if next != NODE_INDEX_NONE {
1123 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(prev);
1124 } else {
1125 let _: &mut NodeTopology = topo[parent_idx].set_last_child(prev);
1126 }
1127 let next_count: u32 = topo[parent_idx].get_child_count().saturating_sub(1);
1128 let _: &mut NodeTopology = topo[parent_idx].set_child_count(next_count);
1129 let _: &mut NodeTopology = topo[child_idx]
1130 .set_parent(NODE_INDEX_NONE)
1131 .set_prev_sibling(NODE_INDEX_NONE)
1132 .set_next_sibling(NODE_INDEX_NONE);
1133 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(None);
1134 let child_z: i32 = self.get_nodes()[child_idx].layout_ref().get_z_index();
1135 if child_z != 0 {
1136 self.recompute_nonzero_z_child(parent_idx);
1137 }
1138 }
1139
1140 fn link_child_tail_at(&mut self, parent_idx: usize, parent_id: NodeId, child_idx: usize) {
1149 let child_u32: u32 = child_idx as u32;
1150 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1151 let tail: u32 = topo[parent_idx].get_last_child();
1152 let _: &mut NodeTopology = topo[child_idx]
1153 .set_parent(parent_idx as u32)
1154 .set_prev_sibling(tail)
1155 .set_next_sibling(NODE_INDEX_NONE);
1156 if tail != NODE_INDEX_NONE {
1157 let _: &mut NodeTopology = topo[tail as usize].set_next_sibling(child_u32);
1158 } else {
1159 let _: &mut NodeTopology = topo[parent_idx].set_first_child(child_u32);
1160 }
1161 let next_count: u32 = topo[parent_idx].get_child_count().saturating_add(1);
1162 let _: &mut NodeTopology = topo[parent_idx]
1163 .set_last_child(child_u32)
1164 .set_child_count(next_count);
1165 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(Some(parent_id));
1166 if self.get_nodes()[child_idx].layout_ref().get_z_index() != 0 {
1167 let next_flags: u16 =
1168 self.get_meta()[parent_idx].get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1169 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(next_flags);
1170 }
1171 }
1172
1173 fn unlink_all_children_at(&mut self, parent_idx: usize) {
1180 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1181 let _: &mut NodeTopology = self.get_mut_topology()[parent_idx]
1182 .set_first_child(NODE_INDEX_NONE)
1183 .set_last_child(NODE_INDEX_NONE)
1184 .set_child_count(0);
1185 let cleared: u16 = self.get_meta()[parent_idx].get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD;
1186 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(cleared);
1187 while cur != NODE_INDEX_NONE {
1188 let ci: usize = cur as usize;
1189 let next: u32 = self.get_topology()[ci].get_next_sibling();
1190 let _: &mut NodeTopology = self.get_mut_topology()[ci]
1191 .set_parent(NODE_INDEX_NONE)
1192 .set_prev_sibling(NODE_INDEX_NONE)
1193 .set_next_sibling(NODE_INDEX_NONE);
1194 let _: &mut SceneNode = self.get_mut_nodes()[ci].set_parent(None);
1195 cur = next;
1196 }
1197 }
1198
1199 pub fn set_children_detached(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
1211 if self.get_node(parent).is_none() {
1212 return false;
1213 }
1214 if self.child_count(parent) == new_children.len()
1215 && self.children_iter(parent).eq(new_children.iter().copied())
1216 {
1217 return false;
1218 }
1219 self.clear_subtree_hover(parent);
1220 let parent_idx: usize = parent.as_usize();
1221 self.unlink_all_children_at(parent_idx);
1222 for child in new_children.iter().copied() {
1223 if child == parent || self.get_node(child).is_none() {
1224 continue;
1225 }
1226 let child_idx: usize = child.as_usize();
1227 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1228 if prev_parent != NODE_INDEX_NONE {
1229 self.unlink_child_at(prev_parent as usize, child_idx);
1230 }
1231 self.link_child_tail_at(parent_idx, parent, child_idx);
1232 }
1233 let dirty_lay: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1234 let dirty_child: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
1235 self.mark_dirty(parent, dirty_lay | dirty_child);
1236 true
1237 }
1238
1239 pub fn replace_child(&mut self, parent: NodeId, old_child: NodeId, new_child: NodeId) -> bool {
1252 if old_child == new_child || new_child == parent {
1253 return false;
1254 }
1255 if self.get_node(parent).is_none()
1256 || self.get_node(old_child).is_none()
1257 || self.get_node(new_child).is_none()
1258 {
1259 return false;
1260 }
1261 let parent_idx: usize = parent.as_usize();
1262 let old_idx: usize = old_child.as_usize();
1263 let new_idx: usize = new_child.as_usize();
1264 if self.get_topology()[old_idx].get_parent() != parent_idx as u32 {
1265 return false;
1266 }
1267 self.clear_subtree_hover(old_child);
1268 let prev_parent: u32 = self.get_topology()[new_idx].get_parent();
1269 if prev_parent != NODE_INDEX_NONE {
1270 self.unlink_child_at(prev_parent as usize, new_idx);
1271 }
1272 let old_topo: NodeTopology = self.get_topology()[old_idx];
1273 let prev: u32 = old_topo.get_prev_sibling();
1274 let next: u32 = old_topo.get_next_sibling();
1275 let new_u32: u32 = new_idx as u32;
1276 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1277 if prev != NODE_INDEX_NONE {
1278 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(new_u32);
1279 } else {
1280 let _: &mut NodeTopology = topo[parent_idx].set_first_child(new_u32);
1281 }
1282 if next != NODE_INDEX_NONE {
1283 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(new_u32);
1284 } else {
1285 let _: &mut NodeTopology = topo[parent_idx].set_last_child(new_u32);
1286 }
1287 let _: &mut NodeTopology = topo[new_idx]
1288 .set_parent(parent_idx as u32)
1289 .set_prev_sibling(prev)
1290 .set_next_sibling(next);
1291 let _: &mut NodeTopology = topo[old_idx]
1292 .set_parent(NODE_INDEX_NONE)
1293 .set_prev_sibling(NODE_INDEX_NONE)
1294 .set_next_sibling(NODE_INDEX_NONE);
1295 let _: &mut SceneNode = self.get_mut_nodes()[old_idx].set_parent(None);
1296 let _: &mut SceneNode = self.get_mut_nodes()[new_idx].set_parent(Some(parent));
1297 let old_z: i32 = self.get_nodes()[old_idx].layout_ref().get_z_index();
1298 let new_z: i32 = self.get_nodes()[new_idx].layout_ref().get_z_index();
1299 self.sync_parent_nonzero_z(parent_idx, old_z, new_z);
1300 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1301 true
1302 }
1303
1304 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
1316 let is_portal: bool = matches!(kind, NodeKind::Portal)
1317 || style.layout_ref().get_position() == Position::Fixed;
1318 let is_scroll: bool = matches!(kind, NodeKind::ScrollView)
1319 || style.layout_ref().get_overflow() == Overflow::Scroll;
1320 let mut init_flags: u16 = NODE_FLAG_ALIVE;
1321 if is_portal {
1322 init_flags |= NODE_FLAG_IS_PORTAL;
1323 }
1324 if is_scroll {
1325 init_flags |= NODE_FLAG_IS_SCROLL_CONTAINER;
1326 }
1327 let effect_entry: PaintEffectEntry =
1328 PaintEffectEntry::from_paint_and_blur(style.paint_ref(), 0.0);
1329 let effect_id: u32 = self.get_mut_effect_table().insert(effect_entry);
1330 let compact_paint: CompactPaintStyle =
1331 CompactPaintStyle::from_paint(style.paint_ref(), effect_id);
1332 let init_sigs: (u64, u64) = compute_style_sigs(&style);
1333 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
1334 let slot_idx: usize = index as usize;
1335 let slot: &mut SceneNode = &mut self.get_mut_nodes()[slot_idx];
1336 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
1337 *slot = SceneNode::new(next_gen, kind, style);
1338 self.get_mut_meta()[slot_idx] = NodeMeta::new(next_gen, init_flags, DIRTY_ALL);
1339 self.get_mut_topology()[slot_idx] = NodeTopology::default();
1340 self.get_mut_compact_paints()[slot_idx] = compact_paint;
1341 if let Some(ep) = self.get_mut_paint_epochs().get_mut(slot_idx) {
1342 *ep = ep.wrapping_add(1);
1343 }
1344 if let Some(sigs) = self.get_mut_style_sigs().get_mut(slot_idx) {
1345 *sigs = init_sigs;
1346 }
1347 NodeId::new(index, next_gen)
1348 } else {
1349 let index: u32 = self.get_nodes().len() as u32;
1350 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
1351 self.get_mut_meta()
1352 .push(NodeMeta::new(1, init_flags, DIRTY_ALL));
1353 self.get_mut_topology().push(NodeTopology::default());
1354 self.get_mut_compact_paints().push(compact_paint);
1355 self.get_mut_paint_epochs().push(0);
1356 self.get_mut_style_sigs().push(init_sigs);
1357 NodeId::new(index, 1)
1358 };
1359 if is_portal {
1360 self.get_mut_portal_nodes().push(id);
1361 self.set_full_damage_pending(true);
1362 self.clear_dirty_paint_queue();
1363 }
1364 if is_scroll {
1365 self.get_mut_scroll_nodes().push(id);
1366 }
1367 let next_live: usize = self.get_live_count().saturating_add(1);
1368 self.set_live_count(next_live);
1369 let next_created: usize = self.get_created_since_damage().saturating_add(1);
1370 self.set_created_since_damage(next_created);
1371 self.set_layout_damage_pending(true);
1372 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
1373 if next_created > DIRTY_PAINT_FULL_THRESHOLD {
1374 self.set_full_damage_pending(true);
1375 self.set_full_damage_overflow(true);
1376 self.clear_dirty_paint_queue();
1377 } else if !self.get_full_damage_pending() {
1378 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1379 self.set_full_damage_pending(true);
1380 self.set_full_damage_overflow(true);
1381 self.clear_dirty_paint_queue();
1382 } else {
1383 self.get_mut_dirty_paint_nodes().push(id);
1384 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1385 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
1386 let _: &mut NodeMeta = meta.set_flags(next_flags);
1387 }
1388 }
1389 }
1390 let next_rev: u64 = self.get_revision().wrapping_add(1);
1391 self.set_revision(next_rev);
1392 notify_frame_needed();
1393 id
1394 }
1395
1396 pub fn create_view(&mut self, style: Style) -> NodeId {
1407 self.create_node(NodeKind::View, style)
1408 }
1409
1410 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
1422 self.create_node(NodeKind::Text(content), style)
1423 }
1424
1425 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1437 self.create_node(NodeKind::Input(state), style)
1438 }
1439
1440 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1452 self.create_node(NodeKind::Image(buffer), style)
1453 }
1454
1455 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
1466 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
1467 }
1468
1469 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
1481 self.create_canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
1482 }
1483
1484 pub fn create_canvas_with_caching(
1497 &mut self,
1498 style: Style,
1499 caching: CanvasCaching,
1500 painter: CanvasDrawCallback,
1501 ) -> NodeId {
1502 let id: NodeId = self.create_node(NodeKind::Canvas(caching), style);
1503 if let Some(node) = self.get_node_mut(id) {
1504 node.set_canvas_painter(Some(painter));
1505 }
1506 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1507 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
1508 let _: &mut NodeMeta = meta.set_flags(next);
1509 }
1510 id
1511 }
1512
1513 pub fn create_portal(&mut self, style: Style) -> NodeId {
1524 self.create_node(NodeKind::Portal, style)
1525 }
1526
1527 pub fn create_fragment(&mut self) -> NodeId {
1537 self.create_node(NodeKind::Fragment, Style::default())
1538 }
1539
1540 #[must_use]
1551 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
1552 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
1553 if node.get_alive() && node.get_generation() == id.get_generation() {
1554 Some(node)
1555 } else {
1556 None
1557 }
1558 }
1559
1560 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
1571 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
1572 if node.get_alive() && node.get_generation() == id.get_generation() {
1573 Some(node)
1574 } else {
1575 None
1576 }
1577 }
1578
1579 #[must_use]
1589 #[inline(always)]
1590 pub fn live_node_count(&self) -> usize {
1591 self.get_live_count()
1592 }
1593
1594 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
1602 if parent == child || self.get_node(parent).is_none() || self.get_node(child).is_none() {
1603 return;
1604 }
1605 let parent_idx: usize = parent.as_usize();
1606 let child_idx: usize = child.as_usize();
1607 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1608 if let Some(old_parent) = prev_parent {
1609 if old_parent != parent {
1610 self.record_subtree_logical_damage(child);
1611 }
1612 self.unlink_child_at(old_parent.as_usize(), child_idx);
1613 if old_parent != parent {
1614 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1615 }
1616 }
1617 self.link_child_tail_at(parent_idx, parent, child_idx);
1618 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1619 }
1620
1621 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
1629 if children.is_empty() || self.get_node(parent).is_none() {
1630 return;
1631 }
1632 let parent_idx: usize = parent.as_usize();
1633 let mut attached_any: bool = false;
1634 for child in children.iter().copied() {
1635 if child == parent || self.get_node(child).is_none() {
1636 continue;
1637 }
1638 let child_idx: usize = child.as_usize();
1639 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1640 if let Some(old_parent) = prev_parent {
1641 if old_parent != parent {
1642 self.record_subtree_logical_damage(child);
1643 }
1644 self.unlink_child_at(old_parent.as_usize(), child_idx);
1645 if old_parent != parent {
1646 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1647 }
1648 }
1649 self.link_child_tail_at(parent_idx, parent, child_idx);
1650 attached_any = true;
1651 }
1652 if attached_any {
1653 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1654 }
1655 }
1656
1657 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
1665 if self.get_node(parent).is_none() {
1666 return;
1667 }
1668 let parent_idx: usize = parent.as_usize();
1669 let old_children: Vec<NodeId> = self.children_vec(parent);
1670 self.unlink_all_children_at(parent_idx);
1671 if new_children.is_empty() {
1672 for old_child in old_children.into_iter() {
1673 self.dispose_subtree(old_child);
1674 }
1675 } else if old_children.len() > 16 && new_children.len() > 16 {
1676 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1677 for old_child in old_children.into_iter() {
1678 if !keep_set.contains(&old_child) {
1679 self.dispose_subtree(old_child);
1680 }
1681 }
1682 } else {
1683 for old_child in old_children.into_iter() {
1684 if !new_children.contains(&old_child) {
1685 self.dispose_subtree(old_child);
1686 }
1687 }
1688 }
1689 for child in new_children.into_iter() {
1690 if child == parent || self.get_node(child).is_none() {
1691 continue;
1692 }
1693 let child_idx: usize = child.as_usize();
1694 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1695 if prev_parent != NODE_INDEX_NONE {
1696 self.unlink_child_at(prev_parent as usize, child_idx);
1697 }
1698 self.link_child_tail_at(parent_idx, parent, child_idx);
1699 }
1700 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1701 }
1702
1703 #[inline]
1714 fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
1715 let same_static: bool = prev.background_color() == next.background_color()
1716 && prev.background_gradient() == next.background_gradient()
1717 && prev.get_border() == next.get_border()
1718 && prev.get_radius() == next.get_radius()
1719 && prev.box_shadow() == next.box_shadow()
1720 && prev.focus_ring_border() == next.focus_ring_border()
1721 && prev.get_cursor() == next.get_cursor()
1722 && prev.get_pointer_events() == next.get_pointer_events();
1723 let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
1724 let composite_changed: bool = prev.get_transform() != next.get_transform()
1725 || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
1726 same_static && same_vis && composite_changed
1727 }
1728
1729 #[inline]
1741 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
1742 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
1743 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
1744 if layout_changed || text_metrics_changed {
1745 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
1746 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
1747 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
1748 Some(next_fixed)
1749 } else {
1750 None
1751 };
1752 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1753 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
1754 let mask: u16 = layout_bits | visual_bits;
1755 return (mask, portal_update);
1756 }
1757 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
1758 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
1759 if paint_changed && !text_visual_changed {
1760 if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
1761 return (DIRTY_COMPOSITE, None);
1762 }
1763 return (DIRTY_PAINT, None);
1764 }
1765 if paint_changed || text_visual_changed {
1766 (DIRTY_PAINT, None)
1767 } else {
1768 (DIRTY_NONE, None)
1769 }
1770 }
1771
1772 #[inline]
1783 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
1784 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
1785 let transform_changed: bool = prev.get_transform() != next.get_transform();
1786 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
1787 let focus_removed: bool =
1788 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
1789 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
1790 let flag_value: bool = shadow_changed || transform_changed;
1791 let is_matched: bool = border_shrank || focus_removed;
1792 let ab: bool = flag_value || is_matched;
1793 ab || opacity_toggled_zero
1794 }
1795
1796 pub fn set_style(&mut self, id: NodeId, style: Style) {
1804 let has_children: bool = self.has_children(id);
1805 let Some(node) = self.get_node(id) else {
1806 return;
1807 };
1808 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
1809 let is_scroll_kind: bool = matches!(node.get_kind(), NodeKind::ScrollView);
1810 let prev: &Style = node.style_ref();
1811 let (dirty_mask, portal_update): (u16, Option<bool>) =
1812 Self::diff_style_change(prev, &style, is_portal_kind);
1813 if dirty_mask == DIRTY_NONE {
1814 return;
1815 }
1816 let prev_scroll: bool =
1817 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1818 let next_scroll: bool =
1819 is_scroll_kind || style.layout_ref().get_overflow() == Overflow::Scroll;
1820 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1821 Some(next_scroll)
1822 } else {
1823 None
1824 };
1825 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
1826 let subtree_hidden: bool = pre_paint
1827 && (prev.paint_ref().get_opacity() > 0.0) != (style.paint_ref().get_opacity() > 0.0)
1828 && has_children;
1829 let prev_z: i32 = prev.layout_ref().get_z_index();
1830 let parent_idx: u32 = self.get_topology()[id.as_usize()].get_parent();
1831 if subtree_hidden {
1832 self.record_subtree_logical_damage(id);
1833 } else if pre_paint {
1834 self.record_node_logical_damage(id);
1835 }
1836 let hiding_now: bool = style.layout_ref().get_display() == Display::None
1837 || style.paint_ref().get_opacity() <= 0.001
1838 || style.paint_ref().get_pointer_events() == PointerEvents::None;
1839 let next_z: i32 = style.layout_ref().get_z_index();
1840 let next_paint: PaintStyle = *style.paint_ref();
1841 if let Some(node) = self.get_node_mut(id) {
1842 node.set_style(style);
1843 }
1844 let blur: f32 = self.backdrop_blur_radius(id);
1845 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1846 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1847 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1848 }
1849 if hiding_now {
1850 self.clear_subtree_hover(id);
1851 }
1852 if let Some(is_portal) = portal_update {
1853 self.sync_portal_registration(id, is_portal);
1854 }
1855 if let Some(is_scroll) = scroll_update {
1856 self.sync_scroll_registration(id, is_scroll);
1857 }
1858 self.mark_dirty(id, dirty_mask);
1859 }
1860
1861 pub fn mutate_style<CallbackFn>(&mut self, id: NodeId, mutator: CallbackFn) -> bool
1873 where
1874 CallbackFn: FnOnce(&mut Style),
1875 {
1876 let has_children: bool = self.has_children(id);
1877 let prev_opt: Option<(Style, bool, bool, u32)> =
1878 self.get_node(id).map(|node: &SceneNode| {
1879 (
1880 *node.style_ref(),
1881 matches!(node.get_kind(), NodeKind::Portal),
1882 matches!(node.get_kind(), NodeKind::ScrollView),
1883 self.get_topology()[id.as_usize()].get_parent(),
1884 )
1885 });
1886 let Some((prev, is_portal_kind, is_scroll_kind, parent_idx)) = prev_opt else {
1887 return false;
1888 };
1889 let mut next: Style = prev;
1890 mutator(&mut next);
1891 let (dirty_mask, portal_update): (u16, Option<bool>) =
1892 Self::diff_style_change(&prev, &next, is_portal_kind);
1893 if dirty_mask == DIRTY_NONE {
1894 return false;
1895 }
1896 let prev_scroll: bool =
1897 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1898 let next_scroll: bool =
1899 is_scroll_kind || next.layout_ref().get_overflow() == Overflow::Scroll;
1900 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1901 Some(next_scroll)
1902 } else {
1903 None
1904 };
1905 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
1906 if pre_paint {
1907 let opacity_toggled_zero: bool =
1908 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
1909 if opacity_toggled_zero && has_children {
1910 self.record_subtree_logical_damage(id);
1911 } else {
1912 self.record_node_logical_damage(id);
1913 }
1914 }
1915 let hiding_now: bool = next.layout_ref().get_display() == Display::None
1916 || next.paint_ref().get_opacity() <= 0.001
1917 || next.paint_ref().get_pointer_events() == PointerEvents::None;
1918 let prev_z: i32 = prev.layout_ref().get_z_index();
1919 let next_z: i32 = next.layout_ref().get_z_index();
1920 let next_paint: PaintStyle = *next.paint_ref();
1921 if let Some(node) = self.get_node_mut(id) {
1922 node.set_style(next);
1923 }
1924 let blur: f32 = self.backdrop_blur_radius(id);
1925 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1926 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1927 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1928 }
1929 if hiding_now {
1930 self.clear_subtree_hover(id);
1931 }
1932 if let Some(is_portal) = portal_update {
1933 self.sync_portal_registration(id, is_portal);
1934 }
1935 if let Some(is_scroll) = scroll_update {
1936 self.sync_scroll_registration(id, is_scroll);
1937 }
1938 self.mark_dirty(id, dirty_mask);
1939 true
1940 }
1941
1942 pub fn set_text(&mut self, id: NodeId, text: String) {
1950 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1951 Some(node) => {
1952 let layout: &LayoutStyle = node.style_ref().layout_ref();
1953 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
1954 && matches!(layout.get_height(), Length::Px(_));
1955 match node.get_mut_kind() {
1956 NodeKind::Text(current) => {
1957 if *current == text {
1958 (false, has_fixed)
1959 } else {
1960 *current = text;
1961 (true, has_fixed)
1962 }
1963 }
1964 _ => (false, false),
1965 }
1966 }
1967 None => (false, false),
1968 };
1969 if changed {
1970 let mask: u16 = if fixed_size {
1971 DIRTY_PAINT
1972 } else {
1973 DIRTY_TEXT_CHANGE_MASK
1974 };
1975 self.mark_dirty(id, mask);
1976 }
1977 }
1978
1979 pub fn set_image(&mut self, id: NodeId, buffer: ImageBuffer) {
1987 let changed: bool = match self.get_node_mut(id) {
1988 Some(node) => {
1989 let same: bool = match node.get_mut_kind() {
1990 NodeKind::Image(existing) => *existing == buffer,
1991 _ => false,
1992 };
1993 if same {
1994 false
1995 } else {
1996 *node.get_mut_kind() = NodeKind::Image(buffer);
1997 true
1998 }
1999 }
2000 None => false,
2001 };
2002 if changed {
2003 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2004 self.mark_dirty(id, dirty_l | DIRTY_PAINT);
2005 notify_frame_needed();
2006 }
2007 }
2008
2009 pub fn set_text_str(&mut self, id: NodeId, text: &str) {
2017 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2018 Some(node) => {
2019 let layout: &LayoutStyle = node.style_ref().layout_ref();
2020 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
2021 && matches!(layout.get_height(), Length::Px(_));
2022 match node.get_mut_kind() {
2023 NodeKind::Text(current) => {
2024 if current.as_str() == text {
2025 (false, has_fixed)
2026 } else {
2027 current.clear();
2028 current.push_str(text);
2029 (true, has_fixed)
2030 }
2031 }
2032 _ => (false, false),
2033 }
2034 }
2035 None => (false, false),
2036 };
2037 if changed {
2038 let mask: u16 = if fixed_size {
2039 DIRTY_PAINT
2040 } else {
2041 DIRTY_TEXT_CHANGE_MASK
2042 };
2043 self.mark_dirty(id, mask);
2044 }
2045 }
2046
2047 pub fn mutate_text<CallbackFn>(&mut self, id: NodeId, mutate: CallbackFn)
2055 where
2056 CallbackFn: FnOnce(&mut String),
2057 {
2058 let (updated, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2059 Some(node) => {
2060 let layout: &LayoutStyle = node.style_ref().layout_ref();
2061 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
2062 && matches!(layout.get_height(), Length::Px(_));
2063 match node.get_mut_kind() {
2064 NodeKind::Text(current) => {
2065 mutate(current);
2066 (true, has_fixed)
2067 }
2068 _ => (false, false),
2069 }
2070 }
2071 None => (false, false),
2072 };
2073 if updated {
2074 let mask: u16 = if fixed_size {
2075 DIRTY_PAINT
2076 } else {
2077 DIRTY_TEXT_CHANGE_MASK
2078 };
2079 self.mark_dirty(id, mask);
2080 }
2081 }
2082
2083 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
2091 let changed: bool = match self.get_node_mut(id) {
2092 Some(node) => {
2093 let layout_box: LayoutBox = node.get_layout_box();
2094 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
2095 && layout_box.get_content_size().get_height() <= 0.0
2096 && layout_box.get_content_bounds().get_width() <= 0.0
2097 && layout_box.get_content_bounds().get_height() <= 0.0;
2098 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
2099 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
2100 } else {
2101 let max_x: f32 = (layout_box.get_content_size().get_width()
2102 - layout_box.get_content_bounds().get_width())
2103 .max(0.0);
2104 let max_y: f32 = (layout_box.get_content_size().get_height()
2105 - layout_box.get_content_bounds().get_height())
2106 .max(0.0);
2107 Point::new(
2108 offset.get_x().clamp(0.0, max_x),
2109 offset.get_y().clamp(0.0, max_y),
2110 )
2111 };
2112 if layout_box.get_scroll_offset() == clamped {
2113 false
2114 } else {
2115 node.get_mut_layout_box().set_scroll_offset(clamped);
2116 true
2117 }
2118 }
2119 None => false,
2120 };
2121 if changed {
2122 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2123 }
2124 }
2125
2126 pub fn request_scroll_into_view(&mut self, target: NodeId) {
2133 if self.live_generation(target).is_none() {
2134 return;
2135 }
2136 let target_parent: Option<NodeId> = self.get_node(target).and_then(SceneNode::parent_id);
2137 let mut retained: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2138 retained.retain(|existing: &NodeId| {
2139 *existing != target
2140 && self.live_generation(*existing).is_some()
2141 && (target_parent.is_none()
2142 || self.get_node(*existing).and_then(SceneNode::parent_id) != target_parent)
2143 });
2144 retained.push(target);
2145 let _: &mut Self = self.set_pending_scroll_into_view(retained);
2146 self.mark_dirty(target, DIRTY_COMPOSITE);
2147 }
2148
2149 pub fn flush_scroll_into_view_requests(&mut self) -> bool {
2161 if self.get_pending_scroll_into_view().is_empty() {
2162 return false;
2163 }
2164 let requests: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2165 let mut any_scrolled: bool = false;
2166 for target in requests.into_iter() {
2167 if self.live_generation(target).is_none() {
2168 continue;
2169 }
2170 if !self.is_node_visible(target) {
2171 self.get_mut_pending_scroll_into_view().push(target);
2172 continue;
2173 }
2174 let Some(target_node) = self.get_node(target) else {
2175 continue;
2176 };
2177 let target_raw: Rect = target_node.get_layout_box().get_bounds();
2178 if target_raw.get_height() <= 0.0 && target_raw.get_width() <= 0.0 {
2179 self.get_mut_pending_scroll_into_view().push(target);
2180 continue;
2181 }
2182 let mut scroll_ancestor: Option<NodeId> = None;
2183 let mut cursor: Option<NodeId> = target_node.parent_id();
2184 while let Some(parent_id) = cursor {
2185 if let Some(parent_node) = self.get_node(parent_id) {
2186 if matches!(parent_node.get_kind(), NodeKind::ScrollView)
2187 || parent_node.style_ref().layout_ref().get_overflow() == Overflow::Scroll
2188 {
2189 scroll_ancestor = Some(parent_id);
2190 break;
2191 }
2192 cursor = parent_node.parent_id();
2193 } else {
2194 break;
2195 }
2196 }
2197 let Some(scroll_id) = scroll_ancestor else {
2198 continue;
2199 };
2200 let Some(scroll_node) = self.get_node(scroll_id) else {
2201 continue;
2202 };
2203 let scroll_box: LayoutBox = scroll_node.get_layout_box();
2204 let view_rect: Rect = scroll_box.get_content_bounds();
2205 if view_rect.get_height() <= 1.0 {
2206 self.get_mut_pending_scroll_into_view().push(target);
2207 continue;
2208 }
2209 let current_scroll: Point = scroll_box.get_scroll_offset();
2210 let visible_top: f32 = target_raw.get_y() - current_scroll.get_y();
2211 let visible_bottom: f32 = target_raw.bottom() - current_scroll.get_y();
2212 if visible_top < view_rect.get_y() || visible_bottom > view_rect.bottom() {
2213 let offset_in_content: f32 = target_raw.get_y() - view_rect.get_y();
2214 let centered_scroll_y: f32 = offset_in_content
2215 - (view_rect.get_height() - target_raw.get_height()).max(0.0) * 0.5;
2216 let before_offset: Point = current_scroll;
2217 self.set_scroll_offset(
2218 scroll_id,
2219 Point::new(current_scroll.get_x(), centered_scroll_y),
2220 );
2221 let after_offset: Point = self
2222 .get_node(scroll_id)
2223 .map(|node_ref: &SceneNode| node_ref.get_layout_box().get_scroll_offset())
2224 .unwrap_or(before_offset);
2225 if after_offset != before_offset {
2226 any_scrolled = true;
2227 }
2228 }
2229 }
2230 any_scrolled
2231 }
2232
2233 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
2242 let mut changed: bool = false;
2243 let mut prev_metrics: Option<(f32, f32)> = None;
2244 let next_metrics: (f32, f32) = (scroll_y.max(0.0), content_height.max(1.0));
2245 let mut scrollbar_bounds: Option<(Rect, f32, f32)> = None;
2246 if let Some(node) = self.get_node_mut(id) {
2247 let prev: Option<(f32, f32)> = node.virtual_scroll_metrics();
2248 prev_metrics = prev;
2249 let next: Option<(f32, f32)> = Some(next_metrics);
2250 if prev != next {
2251 changed = true;
2252 node.set_virtual_scroll(next);
2253 let raw_b: Rect = node.get_layout_box().get_bounds();
2254 let border_width: f32 = node.style_ref().paint_ref().get_border().get_width();
2255 let view_h: f32 = node
2256 .get_layout_box()
2257 .get_content_bounds()
2258 .get_height()
2259 .max(1.0);
2260 if raw_b.get_width() > 0.0 && raw_b.get_height() > 0.0 {
2261 scrollbar_bounds = Some((raw_b, border_width, view_h));
2262 }
2263 }
2264 }
2265 if changed {
2266 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2267 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
2268 let _: &mut NodeMeta = meta.set_flags(next_flags);
2269 }
2270 let show_scrollbar: bool = self
2271 .get_node(self.get_root())
2272 .map(|scene_node: &SceneNode| {
2273 let rb: Rect = scene_node.get_layout_box().get_bounds();
2274 rb.get_width().min(rb.get_height()) >= 540.0
2275 })
2276 .unwrap_or(true);
2277 if !show_scrollbar {
2278 let next_rev: u64 = self.get_revision().wrapping_add(1);
2279 self.set_revision(next_rev);
2280 } else if let Some((raw_b, bloom_width, view_h)) = scrollbar_bounds
2281 && let Some(screen_b) = self.node_screen_bounds(id)
2282 && screen_b.get_width() > 0.0
2283 && screen_b.get_height() > 0.0
2284 {
2285 let inner_y: f32 = screen_b.get_y() + bloom_width;
2286 let inner_h: f32 = (raw_b.get_height() - bloom_width * 2.0).max(1.0);
2287 let track_y: f32 = inner_y + 3.0;
2288 let track_h: f32 = (inner_h - 6.0).max(16.0);
2289 let n_max_sy: f32 = (next_metrics.1 - view_h).max(0.0);
2290 let n_ratio: f32 = (view_h / next_metrics.1.max(view_h)).clamp(0.0, 1.0);
2291 let n_thumb_h: f32 = (track_h * n_ratio).clamp(20.0_f32.min(track_h), track_h);
2292 let n_frac: f32 = if n_max_sy > 1.0 {
2293 (next_metrics.0 / n_max_sy).clamp(0.0, 1.0)
2294 } else {
2295 0.0
2296 };
2297 let ny0: f32 = track_y + (track_h - n_thumb_h) * n_frac;
2298 let ny1: f32 = ny0 + n_thumb_h;
2299 let (y0, y1): (f32, f32) = match prev_metrics {
2300 Some((py, ph)) => {
2301 let p_max_sy: f32 = (ph - view_h).max(0.0);
2302 let p_ratio: f32 = (view_h / ph.max(view_h)).clamp(0.0, 1.0);
2303 let p_thumb_h: f32 =
2304 (track_h * p_ratio).clamp(20.0_f32.min(track_h), track_h);
2305 let p_frac: f32 = if p_max_sy > 1.0 {
2306 (py / p_max_sy).clamp(0.0, 1.0)
2307 } else {
2308 0.0
2309 };
2310 let py0: f32 = track_y + (track_h - p_thumb_h) * p_frac;
2311 let py1: f32 = py0 + p_thumb_h;
2312 (py0.min(ny0) - 4.0, py1.max(ny1) + 4.0)
2313 }
2314 None => (screen_b.get_y(), screen_b.bottom()),
2315 };
2316 let clamped_y0: f32 = y0.max(screen_b.get_y());
2317 let clamped_y1: f32 = y1.min(screen_b.bottom());
2318 let strip_x: f32 = (screen_b.right() - bloom_width - 12.0).max(screen_b.get_x());
2319 let strip_w: f32 = (screen_b.right() - strip_x + 2.0).max(1.0);
2320 let strip_rect: Rect = Rect::new(
2321 strip_x,
2322 clamped_y0,
2323 strip_w,
2324 (clamped_y1 - clamped_y0).max(1.0),
2325 );
2326 if !self.get_full_damage_pending() {
2327 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2328 self.set_full_damage_pending(true);
2329 self.set_full_damage_overflow(true);
2330 self.get_mut_extra_logical_damage().clear();
2331 } else {
2332 self.get_mut_extra_logical_damage().push(strip_rect);
2333 }
2334 }
2335 let next_rev: u64 = self.get_revision().wrapping_add(1);
2336 self.set_revision(next_rev);
2337 } else {
2338 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2339 }
2340 }
2341 }
2342
2343 #[must_use]
2353 pub fn active_webview_node(&self) -> Option<NodeId> {
2354 let Self {
2355 active_webview_node,
2356 ..
2357 } = self;
2358 *active_webview_node
2359 }
2360
2361 pub fn set_active_webview_node(&mut self, node: Option<NodeId>) {
2368 let Self {
2369 active_webview_node,
2370 ..
2371 } = self;
2372 *active_webview_node = node;
2373 }
2374
2375 #[must_use]
2386 pub fn node_effective_opacity(&self, id: NodeId) -> f32 {
2387 let mut combined_alpha: f32 = 1.0;
2388 let mut cursor: Option<NodeId> = Some(id);
2389 while let Some(node_id) = cursor {
2390 let Some(scene_node) = self.get_node(node_id) else {
2391 return 0.0;
2392 };
2393 let style: &Style = scene_node.style_ref();
2394 if style.layout_ref().get_display() == Display::None {
2395 return 0.0;
2396 }
2397 combined_alpha *= style.paint_ref().get_opacity().clamp(0.0, 1.0);
2398 if combined_alpha <= 0.001 {
2399 return 0.0;
2400 }
2401 cursor = scene_node.parent_id();
2402 }
2403 combined_alpha.clamp(0.0, 1.0)
2404 }
2405
2406 #[must_use]
2419 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
2420 let node: &SceneNode = self.get_node(id)?;
2421 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
2422 match self.node_scroll_and_transform(node) {
2423 Some(vals) => vals,
2424 None => return Some(Rect::default()),
2425 };
2426 let raw: Rect = node.get_layout_box().get_bounds();
2427 Some(Rect::new(
2428 raw.get_x() - off.get_x() + tx,
2429 raw.get_y() - off.get_y() + ty,
2430 raw.get_width() * sx,
2431 raw.get_height() * sy,
2432 ))
2433 }
2434
2435 #[inline]
2446 fn node_scroll_and_transform(&self, node: &SceneNode) -> Option<(Point, f32, f32, f32, f32)> {
2447 let style: &Style = node.style_ref();
2448 if style.layout_ref().get_display() == Display::None {
2449 return None;
2450 }
2451 let transform_val: Transform2D = style.paint_ref().get_transform();
2452 let mut tx: f32 = transform_val.get_translate_x();
2453 let mut ty: f32 = transform_val.get_translate_y();
2454 let sx_scale: f32 = transform_val.get_scale_x();
2455 let sy_scale: f32 = transform_val.get_scale_y();
2456 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2457 || style.layout_ref().get_position() == Position::Fixed;
2458 let mut stop_transform: bool = false;
2459 let mut scroll_x: f32 = 0.0;
2460 let mut scroll_y: f32 = 0.0;
2461 let mut cursor: Option<NodeId> = node.parent_id();
2462 while let Some(pid) = cursor {
2463 if let Some(pnode) = self.get_node(pid) {
2464 let pstyle: &Style = pnode.style_ref();
2465 if pstyle.layout_ref().get_display() == Display::None {
2466 return None;
2467 }
2468 if !stop_transform {
2469 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2470 tx += ptr.get_translate_x();
2471 ty += ptr.get_translate_y();
2472 if !start_top_layer {
2473 let off: Point = pnode.get_layout_box().get_scroll_offset();
2474 scroll_x += off.get_x();
2475 scroll_y += off.get_y();
2476 }
2477 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2478 || pstyle.layout_ref().get_position() == Position::Fixed;
2479 if parent_top_layer {
2480 stop_transform = true;
2481 }
2482 }
2483 cursor = pnode.parent_id();
2484 } else {
2485 break;
2486 }
2487 }
2488 Some((Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale))
2489 }
2490
2491 #[must_use]
2504 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
2505 let node: &SceneNode = self.get_node(id)?;
2506 let raw_bounds: Rect = node.get_layout_box().get_bounds();
2507 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
2508 return Some(Rect::default());
2509 }
2510 let style: &Style = node.style_ref();
2511 let paint: &PaintStyle = style.paint_ref();
2512 let transform_val: Transform2D = paint.get_transform();
2513 if transform_val.get_rotation_rad().abs() > 0.0001
2514 || transform_val.get_scale_x() <= 0.0
2515 || transform_val.get_scale_y() <= 0.0
2516 {
2517 return None;
2518 }
2519 let border_w: f32 = paint.get_border().get_width();
2520 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
2521 12.0
2522 } else {
2523 0.0
2524 };
2525 let mut margin: f32 = if border_w > 0.0 {
2526 10.0_f32.max(border_w + 6.0).max(focus_pad)
2527 } else {
2528 4.0_f32.max(focus_pad)
2529 };
2530 if let Some(shadow) = paint.box_shadow() {
2531 let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
2532 let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
2533 let spread: f32 = shadow.get_spread_radius().max(0.0);
2534 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
2535 margin = margin.max(blur_pad + spread + off_max + 4.0);
2536 }
2537 let backdrop_blur: f32 = self.backdrop_blur_radius(id);
2538 if backdrop_blur > 0.0 {
2539 let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
2540 let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
2541 margin = margin.max(blur_halo);
2542 }
2543 let tx: f32 = transform_val.get_translate_x();
2544 let ty: f32 = transform_val.get_translate_y();
2545 let sx: f32 = transform_val.get_scale_x();
2546 let sy: f32 = transform_val.get_scale_y();
2547 let base_rect: Rect = Rect::new(
2548 raw_bounds.get_x() - margin,
2549 raw_bounds.get_y() - margin,
2550 raw_bounds.get_width() + margin * 2.0,
2551 raw_bounds.get_height() + margin * 2.0,
2552 );
2553 let shifted_x: bool = tx != 0.0 || sx != 1.0;
2554 let shifted_y: bool = ty != 0.0 || sy != 1.0;
2555 let mut cur_rect: Rect = if shifted_x || shifted_y {
2556 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
2557 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
2558 let shifted_rect: Rect = Rect::new(
2559 raw_bounds.get_x() + tx - margin - scale_pad_x,
2560 raw_bounds.get_y() + ty - margin - scale_pad_y,
2561 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
2562 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
2563 );
2564 base_rect.union(shifted_rect)
2565 } else {
2566 base_rect
2567 };
2568 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2569 || style.layout_ref().get_position() == Position::Fixed;
2570 let mut cursor: Option<NodeId> = node.parent_id();
2571 while let Some(pid) = cursor {
2572 let Some(pnode) = self.get_node(pid) else {
2573 break;
2574 };
2575 let pstyle: &Style = pnode.style_ref();
2576 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2577 if ptr.get_rotation_rad().abs() > 0.0001
2578 || (ptr.get_scale_x() - 1.0).abs() > 0.001
2579 || (ptr.get_scale_y() - 1.0).abs() > 0.001
2580 {
2581 return None;
2582 }
2583 if !start_top_layer {
2584 let off: Point = pnode.get_layout_box().get_scroll_offset();
2585 cur_rect = Rect::new(
2586 cur_rect.get_x() - off.get_x(),
2587 cur_rect.get_y() - off.get_y(),
2588 cur_rect.get_width(),
2589 cur_rect.get_height(),
2590 );
2591 let p_ov: Overflow = pstyle.layout_ref().get_overflow();
2592 if matches!(p_ov, Overflow::Hidden | Overflow::Scroll) {
2593 let pb: Rect = pnode.get_layout_box().get_bounds();
2594 if pb.get_width() > 0.0 && pb.get_height() > 0.0 {
2595 let clip_box: Rect = Rect::new(
2596 pb.get_x() - 1.0,
2597 pb.get_y() - 1.0,
2598 pb.get_width() + 2.0,
2599 pb.get_height() + 2.0,
2600 );
2601 match cur_rect.intersect(clip_box) {
2602 Some(clipped) => cur_rect = clipped,
2603 None => return Some(Rect::default()),
2604 }
2605 }
2606 }
2607 }
2608 let ptx: f32 = ptr.get_translate_x();
2609 let pty: f32 = ptr.get_translate_y();
2610 if ptx != 0.0 || pty != 0.0 {
2611 cur_rect = Rect::new(
2612 cur_rect.get_x() + ptx,
2613 cur_rect.get_y() + pty,
2614 cur_rect.get_width(),
2615 cur_rect.get_height(),
2616 );
2617 }
2618 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2619 || pstyle.layout_ref().get_position() == Position::Fixed;
2620 if parent_top_layer {
2621 break;
2622 }
2623 cursor = pnode.parent_id();
2624 }
2625 Some(cur_rect)
2626 }
2627
2628 #[must_use]
2639 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
2640 let x0: f32 = (logical.get_x() * scale).floor();
2641 let y0: f32 = (logical.get_y() * scale).floor();
2642 let x1: f32 = (logical.right() * scale).ceil();
2643 let y1: f32 = (logical.bottom() * scale).ceil();
2644 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2645 }
2646
2647 fn record_node_logical_damage(&mut self, id: NodeId) {
2654 if self.get_full_damage_pending() {
2655 return;
2656 }
2657 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
2658 match rect_opt {
2659 Some(rect) => {
2660 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
2661 return;
2662 }
2663 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2664 self.set_full_damage_pending(true);
2665 self.set_full_damage_overflow(true);
2666 self.get_mut_extra_logical_damage().clear();
2667 } else {
2668 self.get_mut_extra_logical_damage().push(rect);
2669 }
2670 }
2671 None => {
2672 self.set_full_damage_pending(true);
2673 }
2674 }
2675 }
2676
2677 fn record_subtree_logical_damage(&mut self, root: NodeId) {
2684 if self.get_full_damage_pending() {
2685 return;
2686 }
2687 let mut stack: Vec<NodeId> = vec![root];
2688 let mut visited: usize = 0;
2689 while let Some(current) = stack.pop() {
2690 let Some(raw_bounds) = self
2691 .get_node(current)
2692 .map(|node: &SceneNode| node.layout_box_ref().get_bounds())
2693 else {
2694 continue;
2695 };
2696 visited += 1;
2697 if visited > DIRTY_PAINT_FULL_THRESHOLD {
2698 self.set_full_damage_pending(true);
2699 self.set_full_damage_overflow(true);
2700 self.get_mut_extra_logical_damage().clear();
2701 return;
2702 }
2703 for child in self.children_iter(current) {
2704 stack.push(child);
2705 }
2706 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
2707 self.record_node_logical_damage(current);
2708 if self.get_full_damage_pending() {
2709 return;
2710 }
2711 }
2712 }
2713 }
2714
2715 pub fn start_transition(&mut self, mut transition: NodeTransition) {
2722 let target: NodeId = transition.get_node();
2723 let had_active: bool = self
2724 .get_transitions()
2725 .iter()
2726 .any(|transform_val: &NodeTransition| transform_val.get_node() == target);
2727 self.get_mut_transitions()
2728 .retain(|object_transform: &NodeTransition| object_transform.get_node() != target);
2729 if had_active && let Some(node) = self.get_node(target) {
2730 let paint: PaintStyle = node.get_style().get_paint();
2731 let transform_val_primary: Transform2D = paint.get_transform();
2732 let cur_op: f32 = paint.get_opacity();
2733 let cur_tx: f32 = transform_val_primary.get_translate_x();
2734 let cur_ty: f32 = transform_val_primary.get_translate_y();
2735 let cur_sc: f32 = transform_val_primary.get_scale_x();
2736 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
2737 .hypot(transition.get_to_ty() - transition.get_from_ty())
2738 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
2739 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
2740 .hypot(transition.get_to_ty() - cur_ty)
2741 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
2742 if full_dist > 0.01 {
2743 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
2744 transition.set_duration((transition.get_duration() * ratio).max(0.05));
2745 }
2746 transition.set_from_opacity(cur_op);
2747 transition.set_from_tx(cur_tx);
2748 transition.set_from_ty(cur_ty);
2749 transition.set_from_scale(cur_sc);
2750 }
2751 self.record_node_logical_damage(target);
2752 let (opacity, transform): (f32, Transform2D) = transition.sample();
2753 let mut unhidden: bool = false;
2754 if let Some(node) = self.get_node_mut(target) {
2755 let style: &mut Style = node.get_mut_style();
2756 if !transition.get_hide_on_complete()
2757 && style.layout_ref().get_display() == Display::None
2758 {
2759 style.get_mut_layout().set_display(Display::Flex);
2760 unhidden = true;
2761 }
2762 style.get_mut_paint().set_opacity(opacity);
2763 style.get_mut_paint().set_transform(transform);
2764 }
2765 if unhidden {
2766 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2767 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2768 } else {
2769 self.mark_dirty(target, DIRTY_COMPOSITE);
2770 }
2771 self.get_mut_transitions().push(transition);
2772 }
2773
2774 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
2785 let len: usize = self.get_transitions().len();
2786 if len == 0 {
2787 return false;
2788 }
2789 let step: f32 = dt_secs.clamp(0.001, 0.05);
2790 let mut any_updated: bool = false;
2791 let mut write_idx: usize = 0;
2792 for read_idx in 0..len {
2793 let target: NodeId = self.get_transitions()[read_idx].get_node();
2794 if self.get_node(target).is_none() {
2795 continue;
2796 }
2797 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
2798 let transform_val: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
2799 let total_span: f32 = transform_val.get_delay() + transform_val.get_duration();
2800 let prev_elapsed: f32 = transform_val.get_elapsed();
2801 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
2802 transform_val.set_elapsed(next_elapsed);
2803 let is_done: bool = transform_val.is_complete();
2804 let in_hold: bool =
2805 prev_elapsed > 0.0 && next_elapsed <= transform_val.get_delay() && !is_done;
2806 if in_hold {
2807 (is_done, None, false)
2808 } else {
2809 let sampled: (f32, Transform2D) = transform_val.sample();
2810 let should_hide: bool = is_done && transform_val.get_hide_on_complete();
2811 (is_done, Some(sampled), should_hide)
2812 }
2813 };
2814 if let Some((opacity, transform)) = sample_opt {
2815 self.record_node_logical_damage(target);
2816 let mut is_portal_hide: bool = false;
2817 if let Some(node) = self.get_node_mut(target) {
2818 is_portal_hide = hide && matches!(node.get_kind(), NodeKind::Portal);
2819 let style: &mut Style = node.get_mut_style();
2820 style.get_mut_paint().set_opacity(opacity);
2821 style.get_mut_paint().set_transform(transform);
2822 if hide {
2823 style.get_mut_layout().set_display(Display::None);
2824 }
2825 }
2826 if hide {
2827 self.clear_subtree_hover(target);
2828 if self
2829 .active_webview_node()
2830 .is_some_and(|webview_id: NodeId| self.is_in_subtree(webview_id, target))
2831 {
2832 self.set_active_webview_node(None);
2833 let _: bool = close_webview_sheet_bridge();
2834 }
2835 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2836 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2837 if is_portal_hide {
2838 self.set_full_damage_pending(true);
2839 self.clear_dirty_paint_queue();
2840 }
2841 } else {
2842 self.mark_dirty(target, DIRTY_COMPOSITE);
2843 }
2844 any_updated = true;
2845 }
2846 if !done {
2847 if write_idx != read_idx {
2848 self.get_mut_transitions().swap(write_idx, read_idx);
2849 }
2850 write_idx += 1;
2851 }
2852 }
2853 self.get_mut_transitions().truncate(write_idx);
2854 any_updated
2855 }
2856
2857 pub fn clear_subtree_hover(&mut self, root: NodeId) {
2864 let hovered_opt: Option<NodeId> = self.get_focus().hovered_node();
2865 if let Some(hovered_id) = hovered_opt
2866 && self.is_in_subtree(hovered_id, root)
2867 {
2868 self.get_mut_focus().set_hovered(None);
2869 let mut walk: Option<NodeId> = Some(hovered_id);
2870 while let Some(cur) = walk {
2871 let mut dirty_paint: bool = false;
2872 let next_parent: Option<NodeId> = if let Some(node) = self.get_node_mut(cur) {
2873 if node.get_interaction().get_hovered() {
2874 node.get_mut_interaction().set_hovered(false);
2875 dirty_paint = node.hover_paint().is_some()
2876 || node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
2877 }
2878 node.parent_id()
2879 } else {
2880 None
2881 };
2882 if dirty_paint {
2883 self.mark_dirty(cur, DIRTY_PAINT);
2884 }
2885 walk = next_parent;
2886 }
2887 }
2888 let pressed_opt: Option<NodeId> = self.get_focus().pressed_node();
2889 if let Some(pressed_id) = pressed_opt
2890 && self.is_in_subtree(pressed_id, root)
2891 {
2892 self.get_mut_focus().set_pressed(None);
2893 if let Some(node) = self.get_node_mut(pressed_id) {
2894 node.get_mut_interaction().set_pressed(false);
2895 }
2896 }
2897 let focused_opt: Option<NodeId> = self.get_focus().focused_node();
2898 if let Some(focused_id) = focused_opt
2899 && self.is_in_subtree(focused_id, root)
2900 {
2901 self.get_mut_focus().set_focused(None);
2902 if let Some(node) = self.get_node_mut(focused_id) {
2903 node.get_mut_interaction().set_focused(false);
2904 }
2905 }
2906 }
2907
2908 #[must_use]
2918 pub fn has_active_transitions(&self) -> bool {
2919 !self.get_transitions().is_empty()
2920 }
2921
2922 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
2930 let attached: bool = if let Some(node) = self.get_node_mut(id) {
2931 node.add_lifecycle(hook);
2932 true
2933 } else {
2934 false
2935 };
2936 if attached {
2937 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2938 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_LIFECYCLE;
2939 let next_flags: u16 = meta.get_flags() | add_flags;
2940 let _: &mut NodeMeta = meta.set_flags(next_flags);
2941 }
2942 let next_lc: usize = self.get_live_lifecycle_count().saturating_add(1);
2943 self.set_live_lifecycle_count(next_lc);
2944 }
2945 }
2946
2947 #[must_use]
2958 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2959 if self.get_live_lifecycle_count() == 0 {
2960 return Vec::new();
2961 }
2962 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = 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_LIFECYCLE) != 0 {
2975 for hook in self.get_nodes()[idx].lifecycle_observers().into_iter() {
2976 out.push((current, hook));
2977 }
2978 }
2979 for child in self.children_iter(current).rev() {
2980 stack.push(child);
2981 }
2982 }
2983 out
2984 }
2985
2986 #[must_use]
2996 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2997 if self.get_live_lifecycle_count() == 0 {
2998 return Vec::new();
2999 }
3000 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3001 let mut stack: Vec<NodeId> = vec![self.get_root()];
3002 while let Some(current) = stack.pop() {
3003 if let Some(node) = self.get_node(current) {
3004 if node.layout_ref().get_display() == Display::None {
3005 continue;
3006 }
3007 if (self.get_meta()[current.as_usize()].get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
3008 {
3009 for hook in node.lifecycle_observers().into_iter() {
3010 out.push((current, hook));
3011 }
3012 }
3013 for child in self.children_iter(current).rev() {
3014 stack.push(child);
3015 }
3016 }
3017 }
3018 out
3019 }
3020
3021 #[must_use]
3032 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
3033 let mut out: Vec<ScopeId> = Vec::new();
3034 let mut stack: Vec<NodeId> = vec![root];
3035 while let Some(current) = stack.pop() {
3036 let idx: usize = current.as_usize();
3037 let Some(meta) = self.get_meta().get(idx) else {
3038 continue;
3039 };
3040 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
3041 || meta.get_generation() != current.get_generation()
3042 {
3043 continue;
3044 }
3045 if (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
3046 && let Some(scope) = self.get_nodes()[idx].owned_scope()
3047 {
3048 out.push(scope.id());
3049 }
3050 for child in self.children_iter(current).rev() {
3051 stack.push(child);
3052 }
3053 }
3054 out
3055 }
3056
3057 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
3064 if self.get_transitions().is_empty() {
3065 return;
3066 }
3067 let mut ids: HashSet<NodeId> = HashSet::new();
3068 let mut stack: Vec<NodeId> = vec![root];
3069 while let Some(current) = stack.pop() {
3070 if ids.insert(current) && self.get_node(current).is_some() {
3071 for child in self.children_iter(current) {
3072 stack.push(child);
3073 }
3074 }
3075 }
3076 self.get_mut_transitions()
3077 .retain(|transform_val: &NodeTransition| !ids.contains(&transform_val.get_node()));
3078 }
3079
3080 pub fn cancel_node_transitions(&mut self, node_id: NodeId) {
3087 if self.get_transitions().is_empty() {
3088 return;
3089 }
3090 self.get_mut_transitions()
3091 .retain(|transform_val: &NodeTransition| transform_val.get_node() != node_id);
3092 }
3093
3094 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
3102 let attached: bool = if let Some(node) = self.get_node_mut(id) {
3103 if let Some(existing) = node.owned_scope() {
3104 existing.enter(|| {
3105 on_cleanup(move || {
3106 scope.dispose();
3107 });
3108 });
3109 } else {
3110 node.set_scope(Some(scope));
3111 }
3112 true
3113 } else {
3114 false
3115 };
3116 if attached && let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
3117 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_SCOPE;
3118 let next_flags: u16 = meta.get_flags() | add_flags;
3119 let _: &mut NodeMeta = meta.set_flags(next_flags);
3120 }
3121 }
3122
3123 #[must_use]
3134 #[inline(always)]
3135 pub(crate) fn node_paint_epoch(&self, id: NodeId) -> u32 {
3136 self.get_paint_epochs()
3137 .get(id.as_usize())
3138 .copied()
3139 .unwrap_or(0)
3140 }
3141
3142 #[must_use]
3152 #[inline(always)]
3153 pub(crate) fn root_has_layout_dirty(&self) -> bool {
3154 let root_id: NodeId = self.get_root();
3155 self.get_node(root_id).is_some_and(|root_node: &SceneNode| {
3156 root_node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
3157 })
3158 }
3159
3160 fn clear_dirty_paint_queue(&mut self) {
3166 let Self {
3167 dirty_paint_nodes,
3168 meta,
3169 ..
3170 } = self;
3171 for nid in dirty_paint_nodes.drain(..) {
3172 if let Some(slot_meta) = meta.get_mut(nid.as_usize()) {
3173 let next_flags: u16 = slot_meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3174 let _: &mut NodeMeta = slot_meta.set_flags(next_flags);
3175 }
3176 }
3177 }
3178
3179 pub fn mark_dirty(&mut self, id: NodeId, mut mask: u16) {
3187 let node_idx: usize = id.as_usize();
3188 if let Some(cur_sigs) = self
3189 .get_node(id)
3190 .map(|node: &SceneNode| compute_style_sigs(node.style_ref()))
3191 && let Some(slot_sigs) = self.get_mut_style_sigs().get_mut(node_idx)
3192 {
3193 let prev_sigs: (u64, u64) = *slot_sigs;
3194 if cur_sigs != prev_sigs {
3195 *slot_sigs = cur_sigs;
3196 if cur_sigs.0 != prev_sigs.0 {
3197 mask |= DIRTY_LAYOUT | DIRTY_PAINT;
3198 }
3199 if cur_sigs.1 != prev_sigs.1 {
3200 mask |= DIRTY_TEXT | DIRTY_LAYOUT;
3201 mask |= DIRTY_PAINT;
3202 }
3203 }
3204 }
3205 let check_layout_registries: bool = (mask & DIRTY_LAYOUT) != 0;
3206 let (mut parent_opt, portal_state, scroll_state, nonzero_z_state): (
3207 Option<NodeId>,
3208 Option<bool>,
3209 Option<bool>,
3210 Option<bool>,
3211 ) = match self.get_node_mut(id) {
3212 Some(node) => {
3213 node.get_mut_dirty().insert(mask);
3214 let (portal_opt, scroll_opt, nz_z_opt): (Option<bool>, Option<bool>, Option<bool>) =
3215 if check_layout_registries {
3216 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
3217 || node.layout_ref().get_position() == Position::Fixed;
3218 let is_scroll: bool = matches!(node.get_kind(), NodeKind::ScrollView)
3219 || node.layout_ref().get_overflow() == Overflow::Scroll;
3220 let has_nz_z: bool = node.layout_ref().get_z_index() != 0;
3221 (Some(is_portal), Some(is_scroll), Some(has_nz_z))
3222 } else {
3223 (None, None, None)
3224 };
3225 (node.parent_id(), portal_opt, scroll_opt, nz_z_opt)
3226 }
3227 None => return,
3228 };
3229 if (mask & (DIRTY_PAINT | DIRTY_FULL_DAMAGE_MASK)) != 0
3230 && let Some(epoch) = self.get_mut_paint_epochs().get_mut(node_idx)
3231 {
3232 *epoch = epoch.wrapping_add(1);
3233 }
3234 let prev_meta_flags: u16 = if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3235 let next_dirty: u16 = meta.get_dirty() | mask;
3236 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3237 meta.get_flags()
3238 } else {
3239 0
3240 };
3241 if let Some(is_portal) = portal_state {
3242 let was_portal: bool = (prev_meta_flags & NODE_FLAG_IS_PORTAL) != 0;
3243 if is_portal != was_portal {
3244 self.sync_portal_registration(id, is_portal);
3245 }
3246 }
3247 if let Some(is_scroll) = scroll_state {
3248 let was_scroll: bool = (prev_meta_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0;
3249 if is_scroll != was_scroll {
3250 self.sync_scroll_registration(id, is_scroll);
3251 }
3252 }
3253 if let Some(has_nz_z) = nonzero_z_state
3254 && let Some(parent_id) = parent_opt
3255 {
3256 let parent_idx: usize = parent_id.as_usize();
3257 if has_nz_z {
3258 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
3259 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
3260 let _: &mut NodeMeta = meta.set_flags(next_flags);
3261 }
3262 } else if self.has_nonzero_z_child(parent_id) {
3263 self.recompute_nonzero_z_child(parent_idx);
3264 }
3265 }
3266 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
3267 self.set_layout_damage_pending(true);
3268 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
3269 }
3270 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3271 if !self.get_full_damage_pending()
3272 && (mask & visual_mask) != 0
3273 && (prev_meta_flags & NODE_FLAG_IN_DIRTY_PAINT_QUEUE) == 0
3274 {
3275 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
3276 self.set_full_damage_pending(true);
3277 self.set_full_damage_overflow(true);
3278 self.clear_dirty_paint_queue();
3279 } else {
3280 self.get_mut_dirty_paint_nodes().push(id);
3281 if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3282 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3283 let _: &mut NodeMeta = meta.set_flags(next_flags);
3284 }
3285 }
3286 }
3287 let mut ancestor_mask: u16 = DIRTY_NONE;
3288 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
3289 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
3290 }
3291 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
3292 ancestor_mask |= DIRTY_SUBTREE_PAINT;
3293 }
3294 if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
3295 ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
3296 }
3297 if ancestor_mask != DIRTY_NONE {
3298 let root_has_mask: bool = {
3299 let root_id: NodeId = self.get_root();
3300 self.get_node(root_id)
3301 .map(|root_node: &SceneNode| {
3302 (root_node.get_dirty().get_bits() & ancestor_mask) == ancestor_mask
3303 })
3304 .unwrap_or(true)
3305 };
3306 let can_early_break: bool = root_has_mask && !self.get_has_stale_hidden_dirty();
3307 while let Some(ancestor_id) = parent_opt {
3308 let ancestor_idx: usize = ancestor_id.as_usize();
3309 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3310 let already: bool =
3311 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
3312 ancestor.get_mut_dirty().insert(ancestor_mask);
3313 parent_opt = ancestor.parent_id();
3314 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3315 let next_dirty: u16 = meta.get_dirty() | ancestor_mask;
3316 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3317 }
3318 if already && can_early_break {
3319 break;
3320 }
3321 } else {
3322 break;
3323 }
3324 }
3325 }
3326 let next_rev: u64 = self.get_revision().wrapping_add(1);
3327 self.set_revision(next_rev);
3328 notify_frame_needed();
3329 }
3330
3331 #[must_use]
3342 pub fn is_node_visible(&self, id: NodeId) -> bool {
3343 let root: NodeId = self.get_root();
3344 let mut cursor: Option<NodeId> = Some(id);
3345 while let Some(cur) = cursor {
3346 let Some(node) = self.get_node(cur) else {
3347 return false;
3348 };
3349 let style: &Style = node.style_ref();
3350 if style.get_layout().get_display() == Display::None
3351 || style.get_paint().get_opacity() <= 0.001
3352 {
3353 return false;
3354 }
3355 if cur == root {
3356 return true;
3357 }
3358 cursor = node.parent_id();
3359 }
3360 false
3361 }
3362
3363 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
3374 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
3375 damage
3376 }
3377
3378 pub(crate) fn collect_surgical_paint_damage(
3390 &mut self,
3391 scale: f32,
3392 allow_partial_layout: bool,
3393 ) -> (DamageRegion, bool) {
3394 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
3395 let layout_pending: bool = self.get_layout_damage_pending();
3396 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
3397 let no_extra: bool = self.get_extra_logical_damage().is_empty();
3398 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
3399 self.set_created_since_damage(0);
3400 self.set_last_collect_composite_only(false);
3401 return (DamageRegion::default(), false);
3402 }
3403 let mut full: bool =
3404 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
3405 let mut saw_paint_or_layout: bool = layout_pending;
3406 let mut saw_composite_or_scroll: bool = false;
3407 let mut region: DamageRegion = DamageRegion::default();
3408 if !full {
3409 let extra_len: usize = self.get_extra_logical_damage().len();
3410 for item_index in 0..extra_len {
3411 let logical_rect: Rect = self.get_extra_logical_damage()[item_index];
3412 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
3413 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3414 }
3415 }
3416 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3417 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3418 for outer_index in 0..dirty_len {
3419 let nid: NodeId = self.get_dirty_paint_nodes()[outer_index];
3420 let Some(node) = self.get_node(nid) else {
3421 continue;
3422 };
3423 let bits: u16 = node.get_dirty().get_bits();
3424 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
3425 if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
3426 saw_paint_or_layout = true;
3427 }
3428 if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
3429 saw_composite_or_scroll = true;
3430 }
3431 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
3432 full = true;
3433 break;
3434 }
3435 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
3436 full = true;
3437 break;
3438 }
3439 if (bits & visual_mask) == 0 {
3440 continue;
3441 }
3442 let raw_bounds: Rect = node.get_layout_box().get_bounds();
3443 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
3444 match self.node_conservative_logical_rect(nid) {
3445 Some(logical_rect) => {
3446 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3447 }
3448 None => {
3449 full = true;
3450 break;
3451 }
3452 }
3453 } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
3454 && !has_layout_bits
3455 && node.style_ref().layout_ref().get_display() != Display::None
3456 {
3457 full = true;
3458 break;
3459 }
3460 }
3461 }
3462 self.set_last_collect_composite_only(
3463 !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
3464 );
3465 self.set_layout_damage_pending(false);
3466 self.set_created_since_damage(0);
3467 self.get_mut_extra_logical_damage().clear();
3468 if !full {
3469 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3470 let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
3471 for step_index in 0..dirty_len {
3472 let nid: NodeId = self.get_dirty_paint_nodes()[step_index];
3473 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
3474 Some(node) => {
3475 node.get_mut_dirty().remove(clear_mask);
3476 node.parent_id()
3477 }
3478 None => None,
3479 };
3480 if let Some(meta) = self.get_mut_meta().get_mut(nid.get_index() as usize) {
3481 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3482 let next_flags: u16 = meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3483 let _: &mut NodeMeta = meta.set_dirty(next_dirty).set_flags(next_flags);
3484 }
3485 while let Some(ancestor_id) = parent_opt {
3486 let ancestor_idx: usize = ancestor_id.get_index() as usize;
3487 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3488 if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
3489 break;
3490 }
3491 ancestor.get_mut_dirty().remove(ancestor_clear);
3492 parent_opt = ancestor.parent_id();
3493 } else {
3494 break;
3495 }
3496 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3497 let next_dirty: u16 = meta.get_dirty() & !ancestor_clear;
3498 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3499 }
3500 }
3501 }
3502 self.get_mut_dirty_paint_nodes().clear();
3503 return (region, layout_pending);
3504 }
3505 self.set_full_damage_pending(false);
3506 self.clear_dirty_paint_queue();
3507 let node_count: usize = self.get_nodes().len();
3508 for idx in 0..node_count {
3509 let should_clear: bool = {
3510 let node: &SceneNode = &self.get_nodes()[idx];
3511 node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0
3512 };
3513 if should_clear {
3514 self.get_mut_nodes()[idx].get_mut_dirty().remove(clear_mask);
3515 if let Some(meta) = self.get_mut_meta().get_mut(idx) {
3516 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3517 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3518 }
3519 }
3520 }
3521 (DamageRegion::full(), layout_pending)
3522 }
3523
3524 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
3534 let was_overflow: bool = self.get_full_damage_overflow();
3535 self.set_full_damage_overflow(false);
3536 was_overflow
3537 }
3538
3539 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
3550 if id == self.get_root() || self.get_node(id).is_none() {
3551 return (Vec::new(), Vec::new());
3552 }
3553 self.record_subtree_logical_damage(id);
3554 self.cancel_subtree_transitions(id);
3555 self.clear_subtree_hover(id);
3556 let root_parent: u32 = self.get_topology()[id.as_usize()].get_parent();
3557 if root_parent != NODE_INDEX_NONE {
3558 self.unlink_child_at(root_parent as usize, id.as_usize());
3559 }
3560 let mut stack: Vec<NodeId> = vec![id];
3561 let mut scopes: Vec<Scope> = Vec::new();
3562 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3563 while let Some(current) = stack.pop() {
3564 let cur_idx: usize = current.as_usize();
3565 let mut next_child: u32 = self.get_topology()[cur_idx].get_first_child();
3566 let mut removed_lifecycles: usize = 0;
3567 let (was_alive, prev_flags): (bool, u16) = match self.get_node_mut(current) {
3568 Some(node) => {
3569 node.set_alive(false);
3570 node.set_kind(NodeKind::View);
3571 if node.has_extras() {
3572 if let Some(scope) = node.owned_scope() {
3573 scopes.push(scope);
3574 }
3575 let drained: Vec<Rc<dyn Lifecycle>> = node.take_lifecycles();
3576 removed_lifecycles = drained.len();
3577 for hook in drained.into_iter() {
3578 observers.push((current, hook));
3579 }
3580 node.clear_extras();
3581 }
3582 node.set_parent(None);
3583 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
3584 node.set_generation(next_gen);
3585 (true, self.get_meta()[cur_idx].get_flags())
3586 }
3587 None => (false, 0),
3588 };
3589 if !was_alive {
3590 continue;
3591 }
3592 while next_child != NODE_INDEX_NONE {
3593 let ci: usize = next_child as usize;
3594 let sibling: u32 = self.get_topology()[ci].get_next_sibling();
3595 let child_gen: u32 = self.get_meta()[ci].get_generation();
3596 stack.push(NodeId::new(next_child, child_gen));
3597 next_child = sibling;
3598 }
3599 let next_gen: u32 = self.get_nodes()[cur_idx].get_generation();
3600 self.get_mut_meta()[cur_idx] = NodeMeta::new(next_gen, 0, DIRTY_NONE);
3601 self.get_mut_topology()[cur_idx] = NodeTopology::default();
3602 let prev_effect_id: u32 = self.get_compact_paints()[cur_idx].get_effect_id();
3603 if prev_effect_id != EFFECT_ID_NONE {
3604 self.get_mut_effect_table().remove(prev_effect_id);
3605 let _: &mut CompactPaintStyle =
3606 self.get_mut_compact_paints()[cur_idx].set_effect_id(EFFECT_ID_NONE);
3607 }
3608 let next_live: usize = self.get_live_count().saturating_sub(1);
3609 self.set_live_count(next_live);
3610 if removed_lifecycles > 0 {
3611 let next_lc: usize = self
3612 .get_live_lifecycle_count()
3613 .saturating_sub(removed_lifecycles);
3614 self.set_live_lifecycle_count(next_lc);
3615 }
3616 if (prev_flags & NODE_FLAG_IS_PORTAL) != 0 && !self.portal_nodes().is_empty() {
3617 self.sync_portal_registration(current, false);
3618 }
3619 if (prev_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0 && !self.scroll_nodes().is_empty()
3620 {
3621 self.sync_scroll_registration(current, false);
3622 }
3623 if !self.get_backdrop_blur_nodes().is_empty() {
3624 self.get_mut_backdrop_blur_nodes()
3625 .retain(|entry: &(NodeId, f32)| entry.0 != current);
3626 }
3627 if self.active_webview_node() == Some(current) {
3628 self.set_active_webview_node(None);
3629 let _: bool = close_webview_sheet_bridge();
3630 }
3631 if self.get_focus().focused_node() == Some(current) {
3632 self.get_mut_focus().set_focused(None);
3633 }
3634 if self.get_focus().hovered_node() == Some(current) {
3635 self.get_mut_focus().set_hovered(None);
3636 }
3637 if self.get_focus().pressed_node() == Some(current) {
3638 self.get_mut_focus().set_pressed(None);
3639 }
3640 let sel_hits_current: bool =
3641 self.text_selection().is_some_and(|sel: SelectionState| {
3642 sel.get_anchor_node() == current || sel.get_focus_node() == current
3643 }) || self
3644 .text_selection_spans_ref()
3645 .iter()
3646 .any(|&(nid, _, _): &(NodeId, usize, usize)| nid == current);
3647 if sel_hits_current {
3648 self.set_text_selection(None);
3649 }
3650 self.get_mut_free_list().push(current.get_index());
3651 }
3652 (scopes, observers)
3653 }
3654
3655 pub fn dispose_subtree(&mut self, id: NodeId) {
3662 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
3663 finalize_disposed_subtree(scopes, observers);
3664 }
3665
3666 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
3677 let prev: Option<NodeId> = self.get_focus().focused_node();
3678 if prev == target {
3679 return Vec::new();
3680 }
3681 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
3682 if let Some(old_id) = prev {
3683 if let Some(old_node) = self.get_node_mut(old_id) {
3684 old_node.get_mut_interaction().set_focused(false);
3685 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
3686 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
3687 }
3688 }
3689 self.mark_dirty(old_id, DIRTY_PAINT);
3690 }
3691 self.get_mut_focus().set_focused(target);
3692 if let Some(new_id) = target {
3693 if let Some(new_node) = self.get_node_mut(new_id) {
3694 new_node.get_mut_interaction().set_focused(true);
3695 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
3696 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
3697 }
3698 }
3699 self.mark_dirty(new_id, DIRTY_PAINT);
3700 }
3701 callbacks
3702 }
3703
3704 #[must_use]
3715 pub fn effective_text_select_mode(&self, id: NodeId) -> TextSelectMode {
3716 let mut cursor: Option<NodeId> = Some(id);
3717 while let Some(cur) = cursor {
3718 let Some(node) = self.get_node(cur) else {
3719 return TextSelectMode::None;
3720 };
3721 if let Some(mode) = node.style_ref().text_ref().text_select_mode() {
3722 return mode;
3723 }
3724 cursor = node.parent_id();
3725 }
3726 TextSelectMode::None
3727 }
3728
3729 #[must_use]
3740 pub fn is_node_selectable(&self, id: NodeId) -> bool {
3741 self.effective_text_select_mode(id) != TextSelectMode::None
3742 }
3743
3744 #[must_use]
3755 pub(crate) fn selectable_scope_root(&self, id: NodeId) -> Option<(NodeId, TextSelectMode)> {
3756 let target_mode: TextSelectMode = self.effective_text_select_mode(id);
3757 if target_mode == TextSelectMode::None {
3758 return None;
3759 }
3760 let mut scope: NodeId = id;
3761 loop {
3762 let cur_node: &SceneNode = self.get_node(scope)?;
3763 if matches!(cur_node.get_kind(), NodeKind::Portal) {
3764 break;
3765 }
3766 let Some(parent_id) = cur_node.parent_id() else {
3767 break;
3768 };
3769 if self.effective_text_select_mode(parent_id) != target_mode {
3770 break;
3771 }
3772 scope = parent_id;
3773 }
3774 Some((scope, target_mode))
3775 }
3776
3777 #[must_use]
3788 pub(crate) fn selectable_scope_text_nodes(&self, id: NodeId) -> Vec<NodeId> {
3789 let Some((scope_root, target_mode)) = self.selectable_scope_root(id) else {
3790 return Vec::new();
3791 };
3792 let mut out: Vec<NodeId> = Vec::new();
3793 let mut stack: Vec<NodeId> = vec![scope_root];
3794 while let Some(cid) = stack.pop() {
3795 let Some(node) = self.get_node(cid) else {
3796 continue;
3797 };
3798 if !node.get_alive() || node.style_ref().get_layout().get_display() == Display::None {
3799 continue;
3800 }
3801 if cid != scope_root {
3802 if matches!(node.get_kind(), NodeKind::Portal) {
3803 continue;
3804 }
3805 if node
3806 .style_ref()
3807 .text_ref()
3808 .text_select_mode()
3809 .is_some_and(|matrix_elems: TextSelectMode| matrix_elems != target_mode)
3810 {
3811 continue;
3812 }
3813 }
3814 if matches!(node.get_kind(), NodeKind::Text(_)) {
3815 out.push(cid);
3816 } else {
3817 let start_len: usize = stack.len();
3818 stack.extend(self.children_iter(cid));
3819 stack[start_len..].reverse();
3820 }
3821 }
3822 out
3823 }
3824
3825 #[must_use]
3836 pub(crate) fn text_node_screen_content_rect(&self, node_id: NodeId) -> Option<Rect> {
3837 let node: &SceneNode = self.get_node(node_id)?;
3838 let computed_box: LayoutBox = node.get_layout_box();
3839 let outer: Rect = computed_box.get_bounds();
3840 let content_rect: Rect = computed_box.get_content_bounds();
3841 let screen_outer: Rect = self.node_screen_bounds(node_id).unwrap_or(outer);
3842 Some(Rect::new(
3843 screen_outer.get_x() + (content_rect.get_x() - outer.get_x()),
3844 screen_outer.get_y() + (content_rect.get_y() - outer.get_y()),
3845 content_rect.get_width(),
3846 content_rect.get_height(),
3847 ))
3848 }
3849
3850 #[must_use]
3862 fn is_new_visual_row(&self, prev_id: NodeId, cur_id: NodeId) -> bool {
3863 let prev_rect: Option<Rect> = self.text_node_screen_content_rect(prev_id);
3864 let cur_rect: Option<Rect> = self.text_node_screen_content_rect(cur_id);
3865 if let (Some(pr), Some(cr)) = (prev_rect, cur_rect)
3866 && pr.get_height() > 0.0
3867 && cr.get_height() > 0.0
3868 {
3869 let prev_cy: f32 = pr.get_y() + pr.get_height() * 0.5;
3870 let cur_cy: f32 = cr.get_y() + cr.get_height() * 0.5;
3871 let threshold: f32 = (pr.get_height().min(cr.get_height()) * 0.5).max(4.0);
3872 return (cur_cy - prev_cy).abs() > threshold;
3873 }
3874 let prev_parent: Option<NodeId> = self.get_node(prev_id).and_then(SceneNode::parent_id);
3875 let cur_parent: Option<NodeId> = self.get_node(cur_id).and_then(SceneNode::parent_id);
3876 if let (Some(pp), Some(cp)) = (prev_parent, cur_parent)
3877 && pp == cp
3878 && let Some(pnode) = self.get_node(pp)
3879 && pnode.style_ref().get_layout().get_flex_direction() == FlexDirection::Row
3880 {
3881 return false;
3882 }
3883 true
3884 }
3885
3886 #[must_use]
3897 fn resolve_selection_spans(&self, selection: SelectionState) -> Vec<(NodeId, usize, usize)> {
3898 if selection.is_empty() {
3899 return Vec::new();
3900 }
3901 if selection.is_single_node() {
3902 let nid: NodeId = selection.get_anchor_node();
3903 let Some(node) = self.get_node(nid) else {
3904 return Vec::new();
3905 };
3906 let NodeKind::Text(content) = node.get_kind() else {
3907 return Vec::new();
3908 };
3909 let len: usize = content.chars().count();
3910 let (raw_s, raw_e): (usize, usize) = selection.ordered_range();
3911 let start_c: usize = raw_s.min(len);
3912 let end_c: usize = raw_e.min(len);
3913 return if start_c < end_c {
3914 vec![(nid, start_c, end_c)]
3915 } else {
3916 Vec::new()
3917 };
3918 }
3919 let anchor_id: NodeId = selection.get_anchor_node();
3920 let focus_id: NodeId = selection.get_focus_node();
3921 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_id);
3922 let anchor_pos: Option<usize> = nodes
3923 .iter()
3924 .position(|target_node_id: &NodeId| *target_node_id == anchor_id);
3925 let focus_pos: Option<usize> = nodes
3926 .iter()
3927 .position(|element_id: &NodeId| *element_id == focus_id);
3928 let (Some(a_pos), Some(f_pos)) = (anchor_pos, focus_pos) else {
3929 return Vec::new();
3930 };
3931 let (start_pos, start_ch, end_pos, end_ch): (usize, usize, usize, usize) = if a_pos <= f_pos
3932 {
3933 (
3934 a_pos,
3935 selection.get_anchor_char(),
3936 f_pos,
3937 selection.get_focus_char(),
3938 )
3939 } else {
3940 (
3941 f_pos,
3942 selection.get_focus_char(),
3943 a_pos,
3944 selection.get_anchor_char(),
3945 )
3946 };
3947 let mut spans: Vec<(NodeId, usize, usize)> =
3948 Vec::with_capacity(end_pos.saturating_sub(start_pos) + 1);
3949 for (idx, &nid) in nodes.iter().enumerate().take(end_pos + 1).skip(start_pos) {
3950 let Some(node) = self.get_node(nid) else {
3951 continue;
3952 };
3953 let NodeKind::Text(content) = node.get_kind() else {
3954 continue;
3955 };
3956 let len: usize = content.chars().count();
3957 let source_val: usize = if idx == start_pos {
3958 start_ch.min(len)
3959 } else {
3960 0
3961 };
3962 let event_ref: usize = if idx == end_pos { end_ch.min(len) } else { len };
3963 if source_val < event_ref || (idx > start_pos && idx < end_pos) {
3964 spans.push((nid, source_val, event_ref));
3965 }
3966 }
3967 spans
3968 }
3969
3970 #[must_use]
3980 pub(crate) fn text_selection_spans_ref(&self) -> &[(NodeId, usize, usize)] {
3981 let Self {
3982 text_selection_spans,
3983 ..
3984 } = self;
3985 text_selection_spans.as_slice()
3986 }
3987
3988 #[must_use]
3999 pub(crate) fn text_selection_range_for(&self, id: NodeId) -> Option<(usize, usize)> {
4000 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4001 if spans.is_empty() {
4002 return None;
4003 }
4004 for &(nid, source_val, event_ref) in spans.iter() {
4005 if nid == id {
4006 return if source_val < event_ref {
4007 Some((source_val, event_ref))
4008 } else {
4009 None
4010 };
4011 }
4012 }
4013 None
4014 }
4015
4016 #[must_use]
4028 pub(crate) fn is_descendant_of(&self, id: NodeId, ancestor: NodeId) -> bool {
4029 let mut cursor: Option<NodeId> = Some(id);
4030 while let Some(cur) = cursor {
4031 if cur == ancestor {
4032 return true;
4033 }
4034 cursor = self.get_node(cur).and_then(SceneNode::parent_id);
4035 }
4036 false
4037 }
4038
4039 #[must_use]
4050 pub fn effective_selection_color(&self, id: NodeId) -> Color {
4051 let mut cursor: Option<NodeId> = Some(id);
4052 while let Some(cur) = cursor {
4053 let Some(node) = self.get_node(cur) else {
4054 break;
4055 };
4056 if let Some(color) = node.style_ref().text_ref().selection_color() {
4057 return color;
4058 }
4059 cursor = node.parent_id();
4060 }
4061 DEFAULT_TEXT_SELECTION_COLOR
4062 }
4063
4064 #[must_use]
4074 pub fn text_selection(&self) -> Option<SelectionState> {
4075 let Self { text_selection, .. } = self;
4076 *text_selection
4077 }
4078
4079 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
4086 let prev: Option<SelectionState> = self.text_selection();
4087 if prev == selection {
4088 return;
4089 }
4090 let mut dirty_ids: Vec<NodeId> =
4091 Vec::with_capacity(self.text_selection_spans_ref().len() + 4);
4092 for &(nid, _, _) in self.text_selection_spans_ref().iter() {
4093 dirty_ids.push(nid);
4094 }
4095 if let Some(old_sel) = prev {
4096 dirty_ids.push(old_sel.get_anchor_node());
4097 if !old_sel.is_single_node() {
4098 dirty_ids.push(old_sel.get_focus_node());
4099 }
4100 }
4101 let next_spans: Vec<(NodeId, usize, usize)> = selection
4102 .map(|sel: SelectionState| self.resolve_selection_spans(sel))
4103 .unwrap_or_default();
4104 for &(nid, _, _) in next_spans.iter() {
4105 dirty_ids.push(nid);
4106 }
4107 if let Some(new_sel) = selection {
4108 dirty_ids.push(new_sel.get_anchor_node());
4109 if !new_sel.is_single_node() {
4110 dirty_ids.push(new_sel.get_focus_node());
4111 }
4112 }
4113 let Self {
4114 text_selection,
4115 text_selection_spans,
4116 ..
4117 } = self;
4118 *text_selection = selection;
4119 *text_selection_spans = next_spans;
4120 for nid in dirty_ids.into_iter() {
4121 self.mark_dirty(nid, DIRTY_PAINT);
4122 }
4123 }
4124
4125 pub fn clear_text_selection(&mut self) {
4131 self.set_text_selection(None);
4132 }
4133
4134 #[must_use]
4145 fn extract_selected_text_filtered(&self, container: Option<NodeId>) -> Option<String> {
4146 let sel: SelectionState = self.text_selection()?;
4147 if sel.is_empty() {
4148 return None;
4149 }
4150 if let Some(root) = container
4151 && !self.is_descendant_of(sel.get_anchor_node(), root)
4152 {
4153 return None;
4154 }
4155 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4156 if spans.is_empty() {
4157 return None;
4158 }
4159 if spans.len() == 1 {
4160 let (nid, source_val, event_ref): (NodeId, usize, usize) = spans[0];
4161 if let Some(root) = container
4162 && !self.is_descendant_of(nid, root)
4163 {
4164 return None;
4165 }
4166 let node: &SceneNode = self.get_node(nid)?;
4167 let NodeKind::Text(content) = node.get_kind() else {
4168 return None;
4169 };
4170 let extracted: &str = extract_char_range(content.as_str(), source_val, event_ref);
4171 return if extracted.is_empty() {
4172 None
4173 } else {
4174 Some(extracted.to_string())
4175 };
4176 }
4177 let mut out: String = String::new();
4178 let mut prev_emitted_node: Option<NodeId> = None;
4179 let last_span_idx: usize = spans.len().saturating_sub(1);
4180 for (idx, &(nid, scale_val, error_val)) in spans.iter().enumerate() {
4181 if let Some(root) = container
4182 && !self.is_descendant_of(nid, root)
4183 {
4184 continue;
4185 }
4186 let Some(node) = self.get_node(nid) else {
4187 continue;
4188 };
4189 let NodeKind::Text(content) = node.get_kind() else {
4190 continue;
4191 };
4192 let part: &str = extract_char_range(content.as_str(), scale_val, error_val);
4193 let is_middle_empty: bool = part.is_empty() && idx > 0 && idx < last_span_idx;
4194 if part.is_empty() && !is_middle_empty {
4195 continue;
4196 }
4197 if let Some(prev_id) = prev_emitted_node
4198 && self.is_new_visual_row(prev_id, nid)
4199 {
4200 out.push('\n');
4201 }
4202 out.push_str(part);
4203 prev_emitted_node = Some(nid);
4204 }
4205 if out.is_empty() { None } else { Some(out) }
4206 }
4207
4208 #[must_use]
4218 pub fn get_selected_text(&self) -> Option<String> {
4219 if let Some(sel) = self.extract_selected_text_filtered(None) {
4220 return Some(sel);
4221 }
4222 let focused: NodeId = self.get_focus().focused_node()?;
4223 let node: &SceneNode = self.get_node(focused)?;
4224 if let NodeKind::Input(state) = node.get_kind() {
4225 return state.selected_text().map(str::to_string);
4226 }
4227 None
4228 }
4229
4230 #[must_use]
4241 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4242 self.extract_selected_text_filtered(Some(container))
4243 }
4244
4245 pub fn select_all_text(&mut self, id: NodeId) -> bool {
4256 if !self.is_node_selectable(id) {
4257 return false;
4258 }
4259 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4260 let Some(&first_id) = nodes.first() else {
4261 return false;
4262 };
4263 let Some(&last_id) = nodes.last() else {
4264 return false;
4265 };
4266 let last_len: usize = self
4267 .get_node(last_id)
4268 .and_then(|node: &SceneNode| {
4269 if let NodeKind::Text(content) = node.get_kind() {
4270 Some(content.chars().count())
4271 } else {
4272 None
4273 }
4274 })
4275 .unwrap_or(0);
4276 if nodes.len() == 1 && last_len == 0 {
4277 return false;
4278 }
4279 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4280 true
4281 }
4282
4283 pub(crate) fn select_line_text(&mut self, id: NodeId) -> bool {
4294 if !self.is_node_selectable(id) {
4295 return false;
4296 }
4297 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4298 let Some(pos) = nodes
4299 .iter()
4300 .position(|target_node_id: &NodeId| *target_node_id == id)
4301 else {
4302 return false;
4303 };
4304 let mut start_idx: usize = pos;
4305 while start_idx > 0 && !self.is_new_visual_row(nodes[start_idx - 1], id) {
4306 start_idx -= 1;
4307 }
4308 let mut end_idx: usize = pos;
4309 while end_idx + 1 < nodes.len() && !self.is_new_visual_row(id, nodes[end_idx + 1]) {
4310 end_idx += 1;
4311 }
4312 let first_id: NodeId = nodes[start_idx];
4313 let last_id: NodeId = nodes[end_idx];
4314 let last_len: usize = self
4315 .get_node(last_id)
4316 .and_then(|node: &SceneNode| {
4317 if let NodeKind::Text(content) = node.get_kind() {
4318 Some(content.chars().count())
4319 } else {
4320 None
4321 }
4322 })
4323 .unwrap_or(0);
4324 if first_id == last_id && last_len == 0 {
4325 return false;
4326 }
4327 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4328 true
4329 }
4330
4331 #[must_use]
4343 pub(crate) fn hit_test_selectable_scope(
4344 &self,
4345 anchor_or_hit: NodeId,
4346 pos: Point,
4347 ) -> Option<(NodeId, usize)> {
4348 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_or_hit);
4349 if nodes.is_empty() {
4350 return None;
4351 }
4352 let mut rects: Vec<(NodeId, Rect, TextStyle, usize)> = Vec::with_capacity(nodes.len());
4353 let mut overall_min_y: f32 = f32::INFINITY;
4354 let mut overall_max_y: f32 = f32::NEG_INFINITY;
4355 for &nid in nodes.iter() {
4356 let Some(node) = self.get_node(nid) else {
4357 continue;
4358 };
4359 let NodeKind::Text(content) = node.get_kind() else {
4360 continue;
4361 };
4362 let Some(rect) = self.text_node_screen_content_rect(nid) else {
4363 continue;
4364 };
4365 let tstyle: TextStyle = node.get_style().get_text();
4366 if pos.get_x() >= rect.get_x()
4367 && pos.get_x() <= rect.right()
4368 && pos.get_y() >= rect.get_y()
4369 && pos.get_y() <= rect.bottom()
4370 {
4371 let ch: usize = hit_test_text_char(content.as_str(), tstyle, rect, pos);
4372 return Some((nid, ch));
4373 }
4374 if rect.get_y() < overall_min_y {
4375 overall_min_y = rect.get_y();
4376 }
4377 if rect.bottom() > overall_max_y {
4378 overall_max_y = rect.bottom();
4379 }
4380 rects.push((nid, rect, tstyle, content.chars().count()));
4381 }
4382 if rects.is_empty() {
4383 return None;
4384 }
4385 if pos.get_y() < overall_min_y - 4.0 {
4386 return Some((rects[0].0, 0));
4387 }
4388 if pos.get_y() > overall_max_y + 4.0 {
4389 let last: (NodeId, Rect, TextStyle, usize) = rects[rects.len() - 1];
4390 return Some((last.0, last.3));
4391 }
4392 let mut min_dy: f32 = f32::INFINITY;
4393 for &(_, rect, _, _) in rects.iter() {
4394 let dy: f32 = if pos.get_y() < rect.get_y() {
4395 rect.get_y() - pos.get_y()
4396 } else if pos.get_y() > rect.bottom() {
4397 pos.get_y() - rect.bottom()
4398 } else {
4399 0.0
4400 };
4401 if dy < min_dy {
4402 min_dy = dy;
4403 }
4404 }
4405 let mut best: Option<(NodeId, Rect, TextStyle, f32, f32)> = None;
4406 for &(nid, rect, tstyle, _) in rects.iter() {
4407 let dy: f32 = if pos.get_y() < rect.get_y() {
4408 rect.get_y() - pos.get_y()
4409 } else if pos.get_y() > rect.bottom() {
4410 pos.get_y() - rect.bottom()
4411 } else {
4412 0.0
4413 };
4414 if dy > min_dy + 2.0 {
4415 continue;
4416 }
4417 let dx: f32 = if pos.get_x() < rect.get_x() {
4418 rect.get_x() - pos.get_x()
4419 } else if pos.get_x() > rect.right() {
4420 pos.get_x() - rect.right()
4421 } else {
4422 0.0
4423 };
4424 let better: bool = match best {
4425 None => true,
4426 Some((_, _, _, b_dx, b_dy)) => dx < b_dx || (dx == b_dx && dy < b_dy),
4427 };
4428 if better {
4429 best = Some((nid, rect, tstyle, dx, dy));
4430 }
4431 }
4432 let (best_nid, best_rect, best_style, _, _): (NodeId, Rect, TextStyle, f32, f32) = best?;
4433 let best_node: &SceneNode = self.get_node(best_nid)?;
4434 let NodeKind::Text(content) = best_node.get_kind() else {
4435 return None;
4436 };
4437 let min_y: f32 = best_rect.get_y() + 0.5;
4438 let max_y: f32 = (best_rect.bottom() - 0.5).max(min_y);
4439 let clamped_y: f32 = pos.get_y().clamp(min_y, max_y);
4440 let ch: usize = hit_test_text_char(
4441 content.as_str(),
4442 best_style,
4443 best_rect,
4444 Point::new(pos.get_x(), clamped_y),
4445 );
4446 Some((best_nid, ch))
4447 }
4448}
4449
4450impl SceneBorrowGuard {
4452 #[inline(always)]
4458 pub(crate) fn enter() -> Self {
4459 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4460 depth.set(depth.get().saturating_add(1));
4461 });
4462 Self
4463 }
4464}
4465
4466impl Drop for SceneBorrowGuard {
4468 #[inline(always)]
4474 fn drop(&mut self) {
4475 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4476 depth.set(depth.get().saturating_sub(1));
4477 });
4478 }
4479}
4480
4481impl SceneHandle {
4483 #[must_use]
4489 pub fn new_tree() -> Self {
4490 Self {
4491 inner: Rc::new(SceneHandleInner {
4492 tree: RefCell::new(SceneTree::default()),
4493 has_deferred: Cell::new(false),
4494 deferred_writes: RefCell::new(Vec::new()),
4495 }),
4496 }
4497 }
4498
4499 #[must_use]
4509 #[inline(always)]
4510 pub fn has_deferred_writes(&self) -> bool {
4511 let Self { inner } = self;
4512 inner.has_deferred.get()
4513 }
4514
4515 fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
4526 let mut executed: usize = 0;
4527 for _ in 0..MAX_FLUSH_ITERATIONS {
4528 let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
4529 Ok(mut queue) => {
4530 inner.has_deferred.set(false);
4531 if queue.is_empty() {
4532 break;
4533 }
4534 take(&mut *queue)
4535 }
4536 Err(_) => break,
4537 };
4538 for op in batch.into_iter() {
4539 op(tree);
4540 executed = executed.saturating_add(1);
4541 }
4542 if !inner.has_deferred.get() {
4543 break;
4544 }
4545 }
4546 executed
4547 }
4548
4549 pub fn flush_deferred_writes(&self) -> usize {
4559 let Self { inner } = self;
4560 if !inner.has_deferred.get() {
4561 return 0;
4562 }
4563 let executed: usize = match inner.tree.try_borrow_mut() {
4564 Ok(mut guard) => {
4565 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4566 Self::drain_deferred_locked(inner, &mut guard)
4567 }
4568 Err(_) => return 0,
4569 };
4570 if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
4571 self.flush_after_outer_borrow();
4572 }
4573 executed
4574 }
4575
4576 #[inline(always)]
4582 fn finish_outer_borrow(&self) {
4583 if is_scene_borrowed() || panicking() {
4584 return;
4585 }
4586 let Self { inner } = self;
4587 if !inner.has_deferred.get() && !has_deferred_effect_flush() {
4588 return;
4589 }
4590 self.flush_after_outer_borrow();
4591 }
4592
4593 #[cold]
4599 fn flush_after_outer_borrow(&self) {
4600 let Self { inner } = self;
4601 for _ in 0..MAX_FLUSH_ITERATIONS {
4602 let drained_writes: usize = if inner.has_deferred.get() {
4603 match inner.tree.try_borrow_mut() {
4604 Ok(mut guard) => {
4605 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4606 Self::drain_deferred_locked(inner, &mut guard)
4607 }
4608 Err(_) => 0,
4609 }
4610 } else {
4611 0
4612 };
4613 let flushed_effects: bool = if take_deferred_effect_flush() {
4614 flush_effects();
4615 true
4616 } else {
4617 false
4618 };
4619 if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
4620 break;
4621 }
4622 }
4623 }
4624
4625 pub fn mutate<CallbackFn>(&self, operation: CallbackFn)
4632 where
4633 CallbackFn: FnOnce(&mut SceneTree) + 'static,
4634 {
4635 let ran_inline: bool = {
4636 let Self { inner } = self;
4637 match inner.tree.try_borrow_mut() {
4638 Ok(mut guard) => {
4639 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4640 operation(&mut guard);
4641 if inner.has_deferred.get() {
4642 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4643 }
4644 true
4645 }
4646 Err(_) => {
4647 if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
4648 queue.push(Box::new(operation));
4649 inner.has_deferred.set(true);
4650 }
4651 notify_frame_needed();
4652 false
4653 }
4654 }
4655 };
4656 if ran_inline {
4657 self.finish_outer_borrow();
4658 }
4659 }
4660
4661 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
4670 self.mutate(move |tree: &mut SceneTree| {
4671 tree.set_virtual_scroll(id, scroll_y, content_height);
4672 });
4673 }
4674
4675 #[must_use]
4686 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
4687 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
4688 }
4689
4690 pub fn start_transition(&self, transition: NodeTransition) {
4697 self.mutate(move |tree: &mut SceneTree| {
4698 tree.start_transition(transition);
4699 });
4700 }
4701
4702 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
4710 self.mutate(move |tree: &mut SceneTree| {
4711 tree.mark_dirty(id, mask);
4712 });
4713 }
4714
4715 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
4723 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4724 |tree: &mut SceneTree| {
4725 if tree.get_node(parent).is_none() {
4726 return (Vec::new(), Vec::new());
4727 }
4728 let parent_idx: usize = parent.as_usize();
4729 let old_children: Vec<NodeId> = tree.children_vec(parent);
4730 tree.unlink_all_children_at(parent_idx);
4731 let mut all_scopes: Vec<Scope> = Vec::new();
4732 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
4733 if new_children.is_empty() {
4734 for old_child in old_children.into_iter() {
4735 let (scale_factor, ob): DisposedSubtreePayload =
4736 tree.dispose_subtree_collect(old_child);
4737 all_scopes.extend(scale_factor);
4738 all_obs.extend(ob);
4739 }
4740 } else if old_children.len() > 16 && new_children.len() > 16 {
4741 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
4742 for old_child in old_children.into_iter() {
4743 if !keep_set.contains(&old_child) {
4744 let (dpi_scale, ob): DisposedSubtreePayload =
4745 tree.dispose_subtree_collect(old_child);
4746 all_scopes.extend(dpi_scale);
4747 all_obs.extend(ob);
4748 }
4749 }
4750 } else {
4751 for old_child in old_children.into_iter() {
4752 if !new_children.contains(&old_child) {
4753 let (scroll_val, ob): DisposedSubtreePayload =
4754 tree.dispose_subtree_collect(old_child);
4755 all_scopes.extend(scroll_val);
4756 all_obs.extend(ob);
4757 }
4758 }
4759 }
4760 for child in new_children.into_iter() {
4761 if child == parent || tree.get_node(child).is_none() {
4762 continue;
4763 }
4764 let child_idx: usize = child.as_usize();
4765 let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
4766 if prev_parent != NODE_INDEX_NONE {
4767 tree.unlink_child_at(prev_parent as usize, child_idx);
4768 }
4769 tree.link_child_tail_at(parent_idx, parent, child_idx);
4770 }
4771 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4772 (all_scopes, all_obs)
4773 },
4774 (Vec::new(), Vec::new()),
4775 );
4776 finalize_disposed_subtree(scopes, observers);
4777 }
4778
4779 pub fn dismiss_portal_immediate(&self, portal: NodeId) {
4786 self.replace_children_safe(portal, Vec::new());
4787 self.with_write(
4788 |tree: &mut SceneTree| {
4789 tree.cancel_subtree_transitions(portal);
4790 tree.clear_subtree_hover(portal);
4791 if let Some(node) = tree.get_node_mut(portal) {
4792 let computed_style: &mut Style = node.get_mut_style();
4793 computed_style.get_mut_layout().set_display(Display::None);
4794 computed_style
4795 .get_mut_paint()
4796 .set_pointer_events(PointerEvents::None)
4797 .set_opacity(0.0);
4798 }
4799 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4800 tree.mark_dirty(portal, dirty_l | DIRTY_PAINT);
4801 tree.set_full_damage_pending(true);
4802 tree.clear_dirty_paint_queue();
4803 },
4804 (),
4805 );
4806 notify_frame_needed();
4807 }
4808
4809 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
4817 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4818 |tree: &mut SceneTree| {
4819 if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
4820 tree.unlink_child_at(parent.as_usize(), child.as_usize());
4821 }
4822 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
4823 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4824 out
4825 },
4826 (Vec::new(), Vec::new()),
4827 );
4828 finalize_disposed_subtree(scopes, observers);
4829 }
4830
4831 pub fn mutate_style<CallbackFn>(&self, id: NodeId, mutator: CallbackFn) -> bool
4843 where
4844 CallbackFn: FnOnce(&mut Style),
4845 {
4846 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
4847 }
4848
4849 pub fn freeze_subtree(&self, root: NodeId) {
4856 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4857 |tree: &mut SceneTree| {
4858 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4859 tree.cancel_subtree_transitions(root);
4860 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
4861 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4862 if layout.get_display() == Display::None {
4863 false
4864 } else {
4865 layout.set_display(Display::None);
4866 true
4867 }
4868 } else {
4869 false
4870 };
4871 if changed {
4872 tree.clear_subtree_hover(root);
4873 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4874 }
4875 obs
4876 },
4877 Vec::new(),
4878 );
4879 dispatch_lifecycle_freeze(&observers);
4880 }
4881
4882 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
4890 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4891 |tree: &mut SceneTree| {
4892 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4893 tree.cancel_subtree_transitions(root);
4894 let mut demoted_fixed: bool = false;
4895 let mut prev_z: i32 = 0;
4896 if let Some(node) = tree.get_node_mut(root) {
4897 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
4898 let computed_style: &mut Style = node.get_mut_style();
4899 prev_z = computed_style.layout_ref().get_z_index();
4900 demoted_fixed =
4901 !is_portal && computed_style.layout_ref().get_position() == Position::Fixed;
4902 computed_style
4903 .get_mut_layout()
4904 .set_position(Position::Absolute)
4905 .set_top(Some(0.0))
4906 .set_right(Some(0.0))
4907 .set_bottom(None)
4908 .set_left(Some(0.0))
4909 .set_z_index(0);
4910 computed_style
4911 .get_mut_paint()
4912 .set_pointer_events(PointerEvents::None);
4913 }
4914 if prev_z != 0 {
4915 let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
4916 if parent_idx != NODE_INDEX_NONE {
4917 tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
4918 }
4919 }
4920 tree.clear_subtree_hover(root);
4921 if demoted_fixed {
4922 tree.sync_portal_registration(root, false);
4923 }
4924 tree.start_transition(exit_transition.with_hide_on_complete(true));
4925 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4926 obs
4927 },
4928 Vec::new(),
4929 );
4930 dispatch_lifecycle_freeze(&observers);
4931 }
4932
4933 pub fn resume_subtree(&self, root: NodeId) {
4940 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4941 |tree: &mut SceneTree| {
4942 let mut unhidden: bool = false;
4943 if let Some(node) = tree.get_node_mut(root) {
4944 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4945 if layout.get_display() == Display::None {
4946 layout.set_display(Display::Flex);
4947 unhidden = true;
4948 }
4949 }
4950 if unhidden {
4951 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4952 } else {
4953 tree.mark_dirty(root, DIRTY_PAINT);
4954 }
4955 tree.collect_subtree_lifecycles(root)
4956 },
4957 Vec::new(),
4958 );
4959 dispatch_lifecycle_resume(&observers);
4960 }
4961
4962 pub fn activate_subtree(&self, root: NodeId) {
4969 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4970 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4971 Vec::new(),
4972 );
4973 dispatch_lifecycle_activate(&observers);
4974 }
4975
4976 pub fn update_subtree(&self, root: NodeId) {
4983 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4984 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4985 Vec::new(),
4986 );
4987 dispatch_lifecycle_update(&observers);
4988 }
4989
4990 pub fn emit_subtree_appear(&self, root: NodeId) {
4997 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4998 |tree: &SceneTree| {
4999 (
5000 tree.collect_subtree_lifecycles(root),
5001 tree.collect_subtree_scope_ids(root),
5002 )
5003 },
5004 (Vec::new(), Vec::new()),
5005 );
5006 let system_event: SystemEvent = SystemEvent::Appear;
5007 dispatch_lifecycle_system_event(&observers, &system_event);
5008 dispatch_system_event_to_scopes(&scopes, &system_event);
5009 }
5010
5011 pub fn emit_subtree_disappear(&self, root: NodeId) {
5018 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
5019 |tree: &SceneTree| {
5020 (
5021 tree.collect_subtree_lifecycles(root),
5022 tree.collect_subtree_scope_ids(root),
5023 )
5024 },
5025 (Vec::new(), Vec::new()),
5026 );
5027 let system_event: SystemEvent = SystemEvent::Disappear;
5028 dispatch_lifecycle_system_event(&observers, &system_event);
5029 dispatch_system_event_to_scopes(&scopes, &system_event);
5030 }
5031
5032 #[must_use]
5042 pub fn has_active_transitions(&self) -> bool {
5043 self.with_read(SceneTree::has_active_transitions, false)
5044 }
5045
5046 #[must_use]
5056 pub fn get_selected_text(&self) -> Option<String> {
5057 self.with_read(SceneTree::get_selected_text, None)
5058 }
5059
5060 #[must_use]
5071 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
5072 self.with_read(
5073 |tree: &SceneTree| tree.get_selected_text_within(container),
5074 None,
5075 )
5076 }
5077
5078 pub fn clear_text_selection(&self) {
5084 self.mutate(SceneTree::clear_text_selection);
5085 }
5086
5087 pub fn with_read<CallbackFn, ReturnValue>(
5099 &self,
5100 operation: CallbackFn,
5101 fallback: ReturnValue,
5102 ) -> ReturnValue
5103 where
5104 CallbackFn: FnOnce(&SceneTree) -> ReturnValue,
5105 {
5106 let result: ReturnValue = {
5107 let Self { inner } = self;
5108 match inner.tree.try_borrow() {
5109 Ok(guard) => {
5110 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5111 operation(&guard)
5112 }
5113 Err(_) => return fallback,
5114 }
5115 };
5116 self.finish_outer_borrow();
5117 result
5118 }
5119
5120 pub fn with_write<CallbackFn, ReturnValue>(
5132 &self,
5133 operation: CallbackFn,
5134 fallback: ReturnValue,
5135 ) -> ReturnValue
5136 where
5137 CallbackFn: FnOnce(&mut SceneTree) -> ReturnValue,
5138 {
5139 let result: ReturnValue = {
5140 let Self { inner } = self;
5141 match inner.tree.try_borrow_mut() {
5142 Ok(mut guard) => {
5143 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5144 let out: ReturnValue = operation(&mut guard);
5145 if inner.has_deferred.get() {
5146 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
5147 }
5148 out
5149 }
5150 Err(_) => return fallback,
5151 }
5152 };
5153 self.finish_outer_borrow();
5154 result
5155 }
5156
5157 pub fn bind_text<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5169 where
5170 CallbackFn: FnMut() -> String + 'static,
5171 {
5172 let handle: Self = self.clone();
5173 Effect::new(move || {
5174 let value: String = producer();
5175 handle.mutate(move |tree: &mut SceneTree| {
5176 tree.set_text(node_id, value);
5177 });
5178 })
5179 }
5180
5181 pub fn bind_style<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5193 where
5194 CallbackFn: FnMut() -> Style + 'static,
5195 {
5196 let handle: Self = self.clone();
5197 Effect::new(move || {
5198 let style: Style = producer();
5199 handle.mutate(move |tree: &mut SceneTree| {
5200 tree.set_style(node_id, style);
5201 });
5202 })
5203 }
5204}
5205
5206impl Drop for ContextShared {
5208 fn drop(&mut self) {
5214 let Self {
5215 owned_signals,
5216 runtime_epoch,
5217 ..
5218 } = self;
5219 if *runtime_epoch != current_runtime_epoch() {
5220 return;
5221 }
5222 for sig_id in owned_signals.iter().copied() {
5223 let dropped: SignalSlot = with_runtime(
5224 |runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_signal(sig_id),
5225 SignalSlot::empty(),
5226 );
5227 drop(dropped);
5228 }
5229 }
5230}
5231
5232impl Context {
5234 #[must_use]
5245 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
5246 let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
5247 let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
5248 let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
5249 let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
5250 let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
5251 let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
5252 let system_back: Signal<u64> = Signal::new_detached(0);
5253 let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
5254 let live_fps: Signal<f32> = Signal::new_detached(60.0);
5255 let present_fps: Signal<f32> = Signal::new_detached(0.0);
5256 let is_idle: Signal<bool> = Signal::new_detached(true);
5257 let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
5258 let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
5259 let exit_requested: Signal<bool> = Signal::new_detached(false);
5260 let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
5261 let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
5262 let keyboard_visible: Signal<bool> = Signal::new_detached(false);
5263 let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
5264 let orientation: Signal<ScreenOrientation> =
5265 Signal::new_detached(ScreenOrientation::Landscape);
5266 let low_power_mode: Signal<bool> = Signal::new_detached(false);
5267 let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
5268 let window_focused: Signal<bool> = Signal::new_detached(true);
5269 let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
5270 let device_motion: Signal<DeviceMotionSample> =
5271 Signal::new_detached(DeviceMotionSample::default());
5272 let owned_signals: [SignalId; 24] = [
5273 breakpoint.id(),
5274 viewport_size.id(),
5275 theme_mode.id(),
5276 safe_area.id(),
5277 gesture.id(),
5278 swipe_drag_offset.id(),
5279 system_back.id(),
5280 fps_limit.id(),
5281 live_fps.id(),
5282 present_fps.id(),
5283 is_idle.id(),
5284 display_refresh_rate.id(),
5285 active_touches.id(),
5286 exit_requested.id(),
5287 app_state.id(),
5288 network_status.id(),
5289 keyboard_visible.id(),
5290 keyboard_height.id(),
5291 orientation.id(),
5292 low_power_mode.id(),
5293 locale.id(),
5294 window_focused.id(),
5295 immersive_fullscreen.id(),
5296 device_motion.id(),
5297 ];
5298 Self {
5299 scene,
5300 breakpoint,
5301 viewport_size,
5302 theme_mode,
5303 platform,
5304 safe_area,
5305 gesture,
5306 swipe_drag_offset,
5307 system_back,
5308 dynamic_hub: DynamicUpdateHub::new(),
5309 fps_limit,
5310 live_fps,
5311 present_fps,
5312 is_idle,
5313 display_refresh_rate,
5314 active_touches,
5315 exit_requested,
5316 app_state,
5317 network_status,
5318 keyboard_visible,
5319 keyboard_height,
5320 orientation,
5321 low_power_mode,
5322 locale,
5323 window_focused,
5324 immersive_fullscreen,
5325 device_motion,
5326 shared: Rc::new(ContextShared {
5327 fullscreen_depth: Cell::new(0),
5328 clock_ms: Cell::new(0),
5329 owned_signals,
5330 runtime_epoch: current_runtime_epoch(),
5331 }),
5332 }
5333 }
5334
5335 #[must_use]
5345 pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
5346 self.get_safe_area()
5347 }
5348
5349 #[must_use]
5359 pub fn safe_area(&self) -> SafeAreaInsets {
5360 self.get_safe_area().get()
5361 }
5362
5363 #[must_use]
5373 pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
5374 self.get_immersive_fullscreen()
5375 }
5376
5377 #[must_use]
5387 pub fn is_immersive_fullscreen(&self) -> bool {
5388 self.get_immersive_fullscreen().get()
5389 }
5390
5391 pub fn set_immersive_fullscreen(&self, enabled: bool) {
5398 let Self { shared, .. } = self;
5399 let changed: bool = if enabled {
5400 if shared.fullscreen_depth.get() == 0 {
5401 shared.fullscreen_depth.set(1);
5402 }
5403 self.get_immersive_fullscreen().set_if_changed(true)
5404 } else {
5405 shared.fullscreen_depth.set(0);
5406 self.get_immersive_fullscreen().set_if_changed(false)
5407 };
5408 if changed {
5409 notify_frame_needed();
5410 }
5411 }
5412
5413 pub fn enter_immersive_fullscreen(&self) {
5419 let Self { shared, .. } = self;
5420 let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
5421 shared.fullscreen_depth.set(next);
5422 if self.get_immersive_fullscreen().set_if_changed(true) {
5423 notify_frame_needed();
5424 }
5425 }
5426
5427 pub fn exit_immersive_fullscreen(&self) {
5433 let Self { shared, .. } = self;
5434 let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
5435 shared.fullscreen_depth.set(next);
5436 if next == 0 && self.get_immersive_fullscreen().set_if_changed(false) {
5437 notify_frame_needed();
5438 }
5439 }
5440
5441 #[must_use]
5451 pub fn app_state_signal(&self) -> Signal<AppState> {
5452 self.get_app_state()
5453 }
5454
5455 pub fn emit_page_appear(&self) {
5461 let system_event: SystemEvent = SystemEvent::Appear;
5462 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5463 .get_scene()
5464 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5465 dispatch_lifecycle_system_event(&observers, &system_event);
5466 dispatch_system_event_listeners(&system_event);
5467 }
5468
5469 pub fn emit_page_disappear(&self) {
5475 let system_event: SystemEvent = SystemEvent::Disappear;
5476 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5477 .get_scene()
5478 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5479 dispatch_lifecycle_system_event(&observers, &system_event);
5480 dispatch_system_event_listeners(&system_event);
5481 }
5482
5483 pub fn emit_subtree_appear(&self, root: NodeId) {
5490 self.get_scene().emit_subtree_appear(root);
5491 }
5492
5493 pub fn emit_subtree_disappear(&self, root: NodeId) {
5500 self.get_scene().emit_subtree_disappear(root);
5501 }
5502
5503 #[must_use]
5513 pub fn elapsed_ms(&self) -> u64 {
5514 let Self { shared, .. } = self;
5515 shared.clock_ms.get()
5516 }
5517
5518 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
5525 let Self { shared, .. } = self;
5526 shared
5527 .clock_ms
5528 .set(shared.clock_ms.get().saturating_add(delta_ms));
5529 }
5530
5531 pub fn request_exit(&self) {
5537 let _: bool = self.get_exit_requested().set_if_changed(true);
5538 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
5539 }
5540
5541 pub fn copy_to_clipboard(&self, text: &str) -> bool {
5552 write_system_clipboard(text)
5553 }
5554
5555 pub fn view(&mut self, style: Style) -> NodeId {
5566 self.get_scene().with_write(
5567 |tree: &mut SceneTree| tree.create_view(style),
5568 NodeId::default(),
5569 )
5570 }
5571
5572 pub fn text(&mut self, content: String, style: Style) -> NodeId {
5584 self.get_scene().with_write(
5585 |tree: &mut SceneTree| tree.create_text(content, style),
5586 NodeId::default(),
5587 )
5588 }
5589
5590 pub fn reactive_text<CallbackFn>(&mut self, style: Style, producer: CallbackFn) -> NodeId
5602 where
5603 CallbackFn: FnMut() -> String + 'static,
5604 {
5605 let node_id: NodeId = self.text(String::new(), style);
5606 let handle: SceneHandle = self.get_scene().clone();
5607 let (scope, _): (Scope, Effect) =
5608 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
5609 self.get_scene().with_write(
5610 |tree: &mut SceneTree| {
5611 tree.attach_scope(node_id, scope);
5612 },
5613 (),
5614 );
5615 node_id
5616 }
5617
5618 pub fn scroll_view(&mut self, style: Style) -> NodeId {
5629 self.get_scene().with_write(
5630 |tree: &mut SceneTree| tree.create_scroll_view(style),
5631 NodeId::default(),
5632 )
5633 }
5634
5635 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
5647 self.get_scene().with_write(
5648 |tree: &mut SceneTree| tree.create_input(state, style),
5649 NodeId::default(),
5650 )
5651 }
5652
5653 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
5665 self.get_scene().with_write(
5666 |tree: &mut SceneTree| tree.create_image(buffer, style),
5667 NodeId::default(),
5668 )
5669 }
5670
5671 pub fn canvas<CallbackFn>(&mut self, style: Style, painter: CallbackFn) -> NodeId
5683 where
5684 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5685 {
5686 self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
5687 }
5688
5689 pub fn canvas_with_caching<CallbackFn>(
5702 &mut self,
5703 style: Style,
5704 caching: CanvasCaching,
5705 painter: CallbackFn,
5706 ) -> NodeId
5707 where
5708 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5709 {
5710 let callback_fn: CanvasDrawCallback = Rc::new(RefCell::new(painter));
5711 self.get_scene().with_write(
5712 |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, callback_fn),
5713 NodeId::default(),
5714 )
5715 }
5716
5717 pub fn portal(&mut self, style: Style) -> NodeId {
5728 self.get_scene().with_write(
5729 |tree: &mut SceneTree| tree.create_portal(style),
5730 NodeId::default(),
5731 )
5732 }
5733
5734 pub fn fragment(&mut self) -> NodeId {
5744 self.get_scene().with_write(
5745 |tree: &mut SceneTree| tree.create_fragment(),
5746 NodeId::default(),
5747 )
5748 }
5749
5750 pub fn append(&mut self, parent: NodeId, child: NodeId) {
5758 self.get_scene().with_write(
5759 |tree: &mut SceneTree| {
5760 tree.append_child(parent, child);
5761 },
5762 (),
5763 );
5764 }
5765
5766 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
5774 if children.is_empty() {
5775 return;
5776 }
5777 self.get_scene().with_write(
5778 |tree: &mut SceneTree| {
5779 tree.append_children(parent, children);
5780 },
5781 (),
5782 );
5783 }
5784
5785 pub fn bind_style<CallbackFn>(&mut self, node_id: NodeId, producer: CallbackFn)
5793 where
5794 CallbackFn: FnMut() -> Style + 'static,
5795 {
5796 let handle: SceneHandle = self.get_scene().clone();
5797 let (scope, _): (Scope, Effect) =
5798 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
5799 self.get_scene().with_write(
5800 |tree: &mut SceneTree| {
5801 tree.attach_scope(node_id, scope);
5802 },
5803 (),
5804 );
5805 }
5806
5807 pub fn on_pointer_enter<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5815 where
5816 CallbackFn: FnMut(&UiEvent) + 'static,
5817 {
5818 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5819 self.get_scene().with_write(
5820 |tree: &mut SceneTree| {
5821 if let Some(node) = tree.get_node_mut(node_id) {
5822 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5823 }
5824 },
5825 (),
5826 );
5827 }
5828
5829 pub fn on_pointer_leave<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5837 where
5838 CallbackFn: FnMut(&UiEvent) + 'static,
5839 {
5840 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5841 self.get_scene().with_write(
5842 |tree: &mut SceneTree| {
5843 if let Some(node) = tree.get_node_mut(node_id) {
5844 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
5845 }
5846 },
5847 (),
5848 );
5849 }
5850
5851 pub fn on_focus<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5859 where
5860 CallbackFn: FnMut(&UiEvent) + 'static,
5861 {
5862 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5863 self.get_scene().with_write(
5864 |tree: &mut SceneTree| {
5865 if let Some(node) = tree.get_node_mut(node_id) {
5866 node.get_mut_handlers().set_on_focus(Some(handler));
5867 node.get_mut_interaction().set_focusable(true);
5868 }
5869 },
5870 (),
5871 );
5872 }
5873
5874 pub fn on_blur<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5882 where
5883 CallbackFn: FnMut(&UiEvent) + 'static,
5884 {
5885 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5886 self.get_scene().with_write(
5887 |tree: &mut SceneTree| {
5888 if let Some(node) = tree.get_node_mut(node_id) {
5889 node.get_mut_handlers().set_on_blur(Some(handler));
5890 }
5891 },
5892 (),
5893 );
5894 }
5895
5896 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
5904 self.get_scene().with_write(
5905 |tree: &mut SceneTree| {
5906 if let Some(node) = tree.get_node_mut(node_id) {
5907 node.get_mut_interaction().set_focusable(focusable);
5908 }
5909 },
5910 (),
5911 );
5912 }
5913
5914 pub fn on_click<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5922 where
5923 CallbackFn: FnMut(&UiEvent) + 'static,
5924 {
5925 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5926 self.get_scene().with_write(
5927 |tree: &mut SceneTree| {
5928 if let Some(node) = tree.get_node_mut(node_id) {
5929 node.get_mut_handlers().set_on_click(Some(handler));
5930 node.get_mut_interaction().set_focusable(true);
5931 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5932 if paint.get_cursor() == CursorIcon::Default {
5933 paint.set_cursor(CursorIcon::Pointer);
5934 }
5935 }
5936 },
5937 (),
5938 );
5939 }
5940
5941 pub fn on_change<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5949 where
5950 CallbackFn: FnMut(&UiEvent) + 'static,
5951 {
5952 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5953 self.get_scene().with_write(
5954 |tree: &mut SceneTree| {
5955 if let Some(node) = tree.get_node_mut(node_id) {
5956 node.get_mut_handlers().set_on_change(Some(handler));
5957 }
5958 },
5959 (),
5960 );
5961 }
5962
5963 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
5971 self.get_scene().with_write(
5972 |tree: &mut SceneTree| {
5973 if let Some(node) = tree.get_node_mut(node_id) {
5974 node.set_a11y(Some(props));
5975 }
5976 },
5977 (),
5978 );
5979 }
5980
5981 pub fn on_scroll<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5989 where
5990 CallbackFn: FnMut(&UiEvent) + 'static,
5991 {
5992 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5993 self.get_scene().with_write(
5994 |tree: &mut SceneTree| {
5995 if let Some(node) = tree.get_node_mut(node_id) {
5996 node.get_mut_handlers().set_on_scroll(Some(handler));
5997 }
5998 },
5999 (),
6000 );
6001 }
6002
6003 pub fn on_pointer_down<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6011 where
6012 CallbackFn: FnMut(&UiEvent) + 'static,
6013 {
6014 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6015 self.get_scene().with_write(
6016 |tree: &mut SceneTree| {
6017 if let Some(node) = tree.get_node_mut(node_id) {
6018 node.get_mut_handlers().set_on_pointer_down(Some(handler));
6019 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
6020 if paint.get_cursor() == CursorIcon::Default {
6021 paint.set_cursor(CursorIcon::Pointer);
6022 }
6023 }
6024 },
6025 (),
6026 );
6027 }
6028
6029 pub fn on_pointer_move<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6037 where
6038 CallbackFn: FnMut(&UiEvent) + 'static,
6039 {
6040 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6041 self.get_scene().with_write(
6042 |tree: &mut SceneTree| {
6043 if let Some(node) = tree.get_node_mut(node_id) {
6044 node.get_mut_handlers().set_on_pointer_move(Some(handler));
6045 }
6046 },
6047 (),
6048 );
6049 }
6050
6051 pub fn on_pointer_up<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6059 where
6060 CallbackFn: FnMut(&UiEvent) + 'static,
6061 {
6062 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6063 self.get_scene().with_write(
6064 |tree: &mut SceneTree| {
6065 if let Some(node) = tree.get_node_mut(node_id) {
6066 node.get_mut_handlers().set_on_pointer_up(Some(handler));
6067 }
6068 },
6069 (),
6070 );
6071 }
6072
6073 pub fn on_pointer_cancel<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6081 where
6082 CallbackFn: FnMut(&UiEvent) + 'static,
6083 {
6084 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6085 self.get_scene().with_write(
6086 |tree: &mut SceneTree| {
6087 if let Some(node) = tree.get_node_mut(node_id) {
6088 node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
6089 }
6090 },
6091 (),
6092 );
6093 }
6094
6095 pub fn on_hover<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6103 where
6104 CallbackFn: FnMut(&UiEvent) + 'static,
6105 {
6106 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6107 let leave_handler: UiEventHandler = handler.clone();
6108 self.get_scene().with_write(
6109 |tree: &mut SceneTree| {
6110 if let Some(node) = tree.get_node_mut(node_id) {
6111 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
6112 node.get_mut_handlers()
6113 .set_on_pointer_leave(Some(leave_handler));
6114 }
6115 },
6116 (),
6117 );
6118 }
6119
6120 pub fn on_key<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6128 where
6129 CallbackFn: FnMut(&UiEvent) + 'static,
6130 {
6131 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6132 self.get_scene().with_write(
6133 |tree: &mut SceneTree| {
6134 if let Some(node) = tree.get_node_mut(node_id) {
6135 node.get_mut_handlers().set_on_key_down(Some(handler));
6136 node.get_mut_interaction().set_focusable(true);
6137 }
6138 },
6139 (),
6140 );
6141 }
6142
6143 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
6152 self.get_scene()
6153 .set_virtual_scroll(node_id, scroll_y, content_height);
6154 }
6155
6156 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
6164 self.get_scene().with_write(
6165 |tree: &mut SceneTree| {
6166 tree.set_scroll_offset(node_id, offset);
6167 },
6168 (),
6169 );
6170 }
6171
6172 pub fn start_transition(&mut self, transition: NodeTransition) {
6179 self.get_scene().start_transition(transition);
6180 }
6181
6182 pub fn bind_children<CallbackFn>(&mut self, host: NodeId, mut builder: CallbackFn)
6190 where
6191 CallbackFn: FnMut() -> Vec<NodeId> + 'static,
6192 {
6193 let ctx_clone: Self = self.clone();
6194 let handle: SceneHandle = self.get_scene().clone();
6195 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6196 Effect::new(move || {
6197 let (child_scope, children): (Scope, Vec<NodeId>) =
6198 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
6199 let first_opt: Option<NodeId> = children.first().copied();
6200 handle.replace_children_safe(host, children);
6201 if let Some(first) = first_opt {
6202 handle.mutate(move |tree: &mut SceneTree| {
6203 tree.attach_scope(first, child_scope);
6204 });
6205 } else {
6206 child_scope.dispose();
6207 }
6208 })
6209 });
6210 self.get_scene().mutate(move |tree: &mut SceneTree| {
6211 tree.attach_scope(host, scope);
6212 });
6213 }
6214
6215 pub fn bind_children_keyed<ValueType, KeyType, Items, KeyFn, RenderFn>(
6225 &mut self,
6226 host: NodeId,
6227 mut items_fn: Items,
6228 mut key_fn: KeyFn,
6229 mut render_fn: RenderFn,
6230 ) where
6231 ValueType: 'static,
6232 KeyType: Eq + Hash + 'static,
6233 Items: FnMut() -> Vec<ValueType> + 'static,
6234 KeyFn: FnMut(&ValueType) -> KeyType + 'static,
6235 RenderFn: FnMut(ValueType) -> NodeId + 'static,
6236 {
6237 let ctx_clone: Self = self.clone();
6238 let handle: SceneHandle = self.get_scene().clone();
6239 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6240 let mut live_nodes: HashMap<KeyType, NodeId> = HashMap::new();
6241 Effect::new(move || {
6242 let next_items: Vec<ValueType> = items_fn();
6243 let mut next_map: HashMap<KeyType, NodeId> =
6244 HashMap::with_capacity(next_items.len());
6245 let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
6246 let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
6247 for item in next_items.into_iter() {
6248 let key: KeyType = key_fn(&item);
6249 if let Some(existing_id) = live_nodes.remove(&key) {
6250 next_children.push(existing_id);
6251 let _: Option<NodeId> = next_map.insert(key, existing_id);
6252 } else {
6253 let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
6254 with_context(ctx_clone.clone(), || render_fn(item))
6255 });
6256 new_scopes.push((mounted_id, item_scope));
6257 next_children.push(mounted_id);
6258 let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
6259 }
6260 }
6261 live_nodes = next_map;
6262 handle.replace_children_safe(host, next_children);
6263 if !new_scopes.is_empty() {
6264 handle.mutate(move |tree: &mut SceneTree| {
6265 for (nid, item_scope) in new_scopes.into_iter() {
6266 tree.attach_scope(nid, item_scope);
6267 }
6268 });
6269 }
6270 })
6271 });
6272 self.get_scene().mutate(move |tree: &mut SceneTree| {
6273 tree.attach_scope(host, scope);
6274 });
6275 }
6276}
6277
6278impl Drop for ContextGuard {
6280 fn drop(&mut self) {
6286 let Self { previous } = self;
6287 let restored: Option<Context> = previous.take();
6288 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
6289 *slot.borrow_mut() = restored;
6290 });
6291 }
6292}
6293
6294impl NodeRefTarget for NodeId {
6296 fn bind_node_ref(&mut self, id: NodeId) {
6303 *self = id;
6304 }
6305}
6306
6307impl NodeRefTarget for Option<NodeId> {
6309 fn bind_node_ref(&mut self, id: NodeId) {
6316 *self = Some(id);
6317 }
6318}
6319
6320impl NodeRefTarget for Cell<NodeId> {
6322 fn bind_node_ref(&mut self, id: NodeId) {
6329 self.set(id);
6330 }
6331}
6332
6333impl NodeRefTarget for Rc<Cell<NodeId>> {
6335 fn bind_node_ref(&mut self, id: NodeId) {
6342 self.set(id);
6343 }
6344}
6345
6346impl NodeRefTarget for Cell<Option<NodeId>> {
6348 fn bind_node_ref(&mut self, id: NodeId) {
6355 self.set(Some(id));
6356 }
6357}
6358
6359impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
6361 fn bind_node_ref(&mut self, id: NodeId) {
6368 self.set(Some(id));
6369 }
6370}
6371
6372impl TextNodeContent for String {
6374 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6386 ctx.text(self, style)
6387 }
6388
6389 fn mount_text_current(self, style: Style) -> NodeId {
6400 with_current_context(|ctx: &Context| {
6401 ctx.get_scene().with_write(
6402 |tree: &mut SceneTree| tree.create_text(self, style),
6403 NodeId::default(),
6404 )
6405 })
6406 }
6407}
6408
6409impl TextNodeContent for &str {
6411 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6423 ctx.text(self.to_string(), style)
6424 }
6425
6426 fn mount_text_current(self, style: Style) -> NodeId {
6437 let owned: String = self.to_string();
6438 with_current_context(|ctx: &Context| {
6439 ctx.get_scene().with_write(
6440 |tree: &mut SceneTree| tree.create_text(owned, style),
6441 NodeId::default(),
6442 )
6443 })
6444 }
6445}
6446
6447impl TextNodeContent for &String {
6449 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6461 ctx.text(self.clone(), style)
6462 }
6463
6464 fn mount_text_current(self, style: Style) -> NodeId {
6475 let owned: String = self.clone();
6476 with_current_context(|ctx: &Context| {
6477 ctx.get_scene().with_write(
6478 |tree: &mut SceneTree| tree.create_text(owned, style),
6479 NodeId::default(),
6480 )
6481 })
6482 }
6483}
6484
6485impl TextNodeContent for Cow<'_, str> {
6487 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6499 ctx.text(self.into_owned(), style)
6500 }
6501
6502 fn mount_text_current(self, style: Style) -> NodeId {
6513 let owned: String = self.into_owned();
6514 with_current_context(|ctx: &Context| {
6515 ctx.get_scene().with_write(
6516 |tree: &mut SceneTree| tree.create_text(owned, style),
6517 NodeId::default(),
6518 )
6519 })
6520 }
6521}
6522
6523impl<CallbackFn, TextValue> TextNodeContent for CallbackFn
6525where
6526 CallbackFn: FnMut() -> TextValue + 'static,
6527 TextValue: Into<String>,
6528{
6529 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
6541 ctx.reactive_text(style, move || self().into())
6542 }
6543
6544 fn mount_text_current(mut self, style: Style) -> NodeId {
6555 mount_reactive_text(style, move || self().into())
6556 }
6557}