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 topology_revision: 1,
124 transitions: Vec::new(),
125 caret_visible: true,
126 portal_nodes: Vec::new(),
127 scroll_nodes: Vec::new(),
128 dirty_paint_nodes: Vec::new(),
129 full_damage_pending: true,
130 layout_damage_pending: true,
131 full_damage_overflow: false,
132 created_since_damage: 0,
133 extra_logical_damage: Vec::new(),
134 text_selection: None,
135 text_selection_spans: Vec::new(),
136 backdrop_blur_nodes: Vec::new(),
137 layout_invalidations: 1,
138 last_collect_composite_only: false,
139 theme_entries: HashMap::new(),
140 paint_epochs: vec![0],
141 node_mutation_epochs: vec![1],
142 serial_layout_epoch: 0,
143 style_sigs: vec![root_sigs],
144 has_stale_hidden_dirty: false,
145 pending_scroll_into_view: Vec::new(),
146 active_webview_node: None,
147 }
148 }
149}
150
151impl SceneTree {
153 fn live_generation(&self, id: NodeId) -> Option<u32> {
164 let meta: &NodeMeta = self.get_meta().get(id.as_usize())?;
165 ((meta.get_flags() & NODE_FLAG_ALIVE) != 0 && meta.get_generation() == id.get_generation())
166 .then_some(id.get_generation())
167 }
168
169 fn theme_entry(&self, id: NodeId) -> Option<ThemeNodeEntry> {
180 let generation: u32 = self.live_generation(id)?;
181 let Self { theme_entries, .. } = self;
182 theme_entries
183 .get(&id.get_index())
184 .copied()
185 .filter(|entry: &ThemeNodeEntry| entry.get_generation() == generation)
186 }
187
188 fn update_theme_entry<CallbackFn>(&mut self, id: NodeId, apply: CallbackFn)
196 where
197 CallbackFn: FnOnce(&mut ThemeNodeEntry),
198 {
199 let Some(generation) = self.live_generation(id) else {
200 return;
201 };
202 let Self { theme_entries, .. } = self;
203 let entry: &mut ThemeNodeEntry = theme_entries
204 .entry(id.get_index())
205 .or_insert_with(|| ThemeNodeEntry::new(generation, false, None));
206 if entry.get_generation() != generation {
207 *entry = ThemeNodeEntry::new(generation, false, None);
208 }
209 apply(entry);
210 }
211
212 pub fn set_theme_owned(&mut self, id: NodeId, owned: bool) {
220 if !owned && self.theme_entry(id).is_none() {
221 return;
222 }
223 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
224 entry.set_owned(owned);
225 });
226 }
227
228 #[must_use]
239 pub fn is_theme_owned(&self, id: NodeId) -> bool {
240 self.theme_entry(id)
241 .is_some_and(|entry: ThemeNodeEntry| entry.get_owned())
242 }
243
244 #[must_use]
255 pub fn theme_baseline(&self, id: NodeId) -> Option<ThemeBaseline> {
256 self.theme_entry(id)
257 .and_then(|entry: ThemeNodeEntry| entry.get_baseline())
258 }
259
260 pub fn set_theme_baseline(&mut self, id: NodeId, baseline: Option<ThemeBaseline>) {
268 if baseline.is_none() && self.theme_entry(id).is_none() {
269 return;
270 }
271 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
272 entry.set_baseline(baseline);
273 });
274 }
275}
276
277impl SceneTree {
279 pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
287 if self.get_node(id).is_none() {
288 return;
289 }
290 let clamped: f32 = if blur_radius.is_finite() {
291 blur_radius.clamp(0.0, 96.0)
292 } else {
293 0.0
294 };
295 let prev_radius: f32 = self.backdrop_blur_radius(id);
296 if (prev_radius - clamped).abs() <= 0.001 {
297 return;
298 }
299 if prev_radius > 0.0 {
300 self.record_node_logical_damage(id);
301 }
302 let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
303 if clamped <= 0.0 {
304 blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
305 } else if let Some(slot) = blurs
306 .iter_mut()
307 .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
308 {
309 slot.1 = clamped;
310 } else {
311 blurs.push((id, clamped));
312 }
313 let paint_copy: Option<PaintStyle> =
314 self.get_node(id).map(|node: &SceneNode| *node.paint_ref());
315 if let Some(paint) = paint_copy {
316 self.sync_node_compact_paint(id.as_usize(), &paint, clamped);
317 }
318 self.mark_dirty(id, DIRTY_PAINT);
319 }
320
321 #[must_use]
332 pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
333 for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
334 if nid == id {
335 return radius;
336 }
337 }
338 0.0
339 }
340
341 #[must_use]
351 pub fn has_backdrop_blur_nodes(&self) -> bool {
352 !self.get_backdrop_blur_nodes().is_empty()
353 }
354
355 pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
367 if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
368 return 0;
369 }
370 let clamped_scale: f32 = scale.max(0.5);
371 let blur_count: usize = self.get_backdrop_blur_nodes().len();
372 let mut dirtied: Vec<bool> = vec![false; blur_count];
373 let mut total_added: usize = 0;
374 let mut changed: bool = true;
375 while changed && !damage.get_full_damage() {
376 changed = false;
377 if damage.bounds_rect().is_none() {
378 break;
379 }
380 for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
381 if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
382 continue;
383 }
384 let Some(screen_rect) = self.node_screen_bounds(nid) else {
385 continue;
386 };
387 if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
388 continue;
389 }
390 let sigma: f32 = (blur_radius * 0.5).max(0.75);
391 let halo: f32 = (sigma * 3.0).ceil() + 2.0;
392 let sample_logical: Rect = Rect::new(
393 screen_rect.get_x() - halo,
394 screen_rect.get_y() - halo,
395 screen_rect.get_width() + halo * 2.0,
396 screen_rect.get_height() + halo * 2.0,
397 );
398 let sample_phys: Rect =
399 Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
400 let output_phys: Rect = Self::scale_logical_to_phys_rect(
401 Rect::new(
402 screen_rect.get_x() - 2.0,
403 screen_rect.get_y() - 2.0,
404 screen_rect.get_width() + 4.0,
405 screen_rect.get_height() + 4.0,
406 ),
407 clamped_scale,
408 );
409 let (rects, count): ([Rect; 8], usize) =
410 damage.normalized_rects(u32::MAX, u32::MAX);
411 let overlaps: bool = rects
412 .iter()
413 .take(count)
414 .any(|rect_bounds: &Rect| rect_bounds.intersect(sample_phys).is_some());
415 if overlaps {
416 damage.add_rect(output_phys);
417 dirtied[idx] = true;
418 total_added += 1;
419 changed = true;
420 }
421 }
422 }
423 total_added
424 }
425
426 pub fn effect_dependency_damage(
442 &self,
443 dirty_set: &mut DirtyRectSet,
444 extra_portals: &[PortalBackdropRegion],
445 viewport_w: u32,
446 viewport_h: u32,
447 scale: f32,
448 full_ratio_threshold: f32,
449 ) -> EffectDamageReport {
450 if dirty_set.get_full_frame() {
451 return EffectDamageReport::new(
452 0,
453 extra_portals.len() + self.get_backdrop_blur_nodes().len(),
454 true,
455 );
456 }
457 let mut combined: Vec<PortalBackdropRegion> =
458 Vec::with_capacity(extra_portals.len() + self.get_backdrop_blur_nodes().len());
459 combined.extend_from_slice(extra_portals);
460 for &(nid, blur_radius) in self.get_backdrop_blur_nodes().iter() {
461 if blur_radius <= 0.0 || !self.is_node_visible(nid) {
462 continue;
463 }
464 if let Some(screen_rect) = self.node_screen_bounds(nid)
465 && screen_rect.get_width() > 0.0
466 && screen_rect.get_height() > 0.0
467 {
468 let is_dirty: bool = self
469 .get_node(nid)
470 .map(|scene_node: &SceneNode| scene_node.get_dirty().get_bits() != DIRTY_NONE)
471 .unwrap_or(false);
472 combined.push(PortalBackdropRegion::new(
473 screen_rect,
474 blur_radius,
475 is_dirty,
476 ));
477 }
478 }
479 dirty_set.apply_effect_dependency_damage(
480 &combined,
481 viewport_w,
482 viewport_h,
483 scale,
484 full_ratio_threshold,
485 )
486 }
487
488 #[must_use]
498 #[inline(always)]
499 pub fn portal_nodes(&self) -> &[NodeId] {
500 let Self { portal_nodes, .. } = self;
501 portal_nodes.as_slice()
502 }
503
504 #[must_use]
514 #[inline(always)]
515 pub fn has_portal_nodes(&self) -> bool {
516 let Self { portal_nodes, .. } = self;
517 !portal_nodes.is_empty()
518 }
519
520 fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
528 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
529 let next: u16 = if is_portal {
530 meta.get_flags() | NODE_FLAG_IS_PORTAL
531 } else {
532 meta.get_flags() & !NODE_FLAG_IS_PORTAL
533 };
534 let _: &mut NodeMeta = meta.set_flags(next);
535 }
536 let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
537 if is_portal {
538 if !portals.contains(&id) {
539 portals.push(id);
540 }
541 } else if !portals.is_empty() {
542 portals.retain(|existing: &NodeId| *existing != id);
543 }
544 }
545
546 #[must_use]
556 #[inline(always)]
557 pub fn scroll_nodes(&self) -> &[NodeId] {
558 let Self { scroll_nodes, .. } = self;
559 scroll_nodes.as_slice()
560 }
561
562 #[must_use]
572 #[inline(always)]
573 pub fn has_scroll_nodes(&self) -> bool {
574 let Self { scroll_nodes, .. } = self;
575 !scroll_nodes.is_empty()
576 }
577
578 fn sync_scroll_registration(&mut self, id: NodeId, is_scroll: bool) {
586 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
587 let next: u16 = if is_scroll {
588 meta.get_flags() | NODE_FLAG_IS_SCROLL_CONTAINER
589 } else {
590 meta.get_flags() & !NODE_FLAG_IS_SCROLL_CONTAINER
591 };
592 let _: &mut NodeMeta = meta.set_flags(next);
593 }
594 let scrolls: &mut Vec<NodeId> = self.get_mut_scroll_nodes();
595 if is_scroll {
596 if !scrolls.contains(&id) {
597 scrolls.push(id);
598 }
599 } else if !scrolls.is_empty() {
600 scrolls.retain(|existing: &NodeId| *existing != id);
601 }
602 }
603
604 fn sync_node_compact_paint(&mut self, idx: usize, paint: &PaintStyle, blur: f32) {
613 let prev_effect_id: u32 = self
614 .get_compact_paints()
615 .get(idx)
616 .map(CompactPaintStyle::get_effect_id)
617 .unwrap_or(EFFECT_ID_NONE);
618 let entry: PaintEffectEntry = PaintEffectEntry::from_paint_and_blur(paint, blur);
619 let next_effect_id: u32 = self.get_mut_effect_table().update(prev_effect_id, entry);
620 let compact: CompactPaintStyle = CompactPaintStyle::from_paint(paint, next_effect_id);
621 if let Some(slot) = self.get_mut_compact_paints().get_mut(idx) {
622 *slot = compact;
623 }
624 }
625
626 #[must_use]
637 #[inline(always)]
638 pub fn compact_paint(&self, id: NodeId) -> Option<&CompactPaintStyle> {
639 let idx: usize = id.as_usize();
640 let meta: &NodeMeta = self.get_meta().get(idx)?;
641 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
642 {
643 return None;
644 }
645 self.get_compact_paints().get(idx)
646 }
647
648 #[must_use]
659 #[inline(always)]
660 pub fn paint_effect(&self, id: NodeId) -> Option<&PaintEffectEntry> {
661 let effect_id: u32 = self.compact_paint(id)?.get_effect_id();
662 self.get_effect_table().get(effect_id)
663 }
664
665 #[must_use]
675 #[inline(always)]
676 pub fn effect_table(&self) -> &EffectTable {
677 self.get_effect_table()
678 }
679
680 #[must_use]
691 #[inline(always)]
692 pub fn has_extras(&self, id: NodeId) -> bool {
693 let Some(node) = self.get_node(id) else {
694 return false;
695 };
696 node.has_extras()
697 }
698
699 #[must_use]
710 #[inline(always)]
711 pub fn has_nonzero_z_child(&self, id: NodeId) -> bool {
712 let idx: usize = id.as_usize();
713 let Some(meta) = self.get_meta().get(idx) else {
714 return false;
715 };
716 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
717 && meta.get_generation() == id.get_generation()
718 && (meta.get_flags() & NODE_FLAG_HAS_NONZERO_Z_CHILD) != 0
719 }
720
721 #[must_use]
732 #[inline(always)]
733 pub fn has_lifecycle(&self, id: NodeId) -> bool {
734 let idx: usize = id.as_usize();
735 let Some(meta) = self.get_meta().get(idx) else {
736 return false;
737 };
738 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
739 && meta.get_generation() == id.get_generation()
740 && (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
741 }
742
743 #[must_use]
754 #[inline(always)]
755 pub fn has_scope(&self, id: NodeId) -> bool {
756 let idx: usize = id.as_usize();
757 let Some(meta) = self.get_meta().get(idx) else {
758 return false;
759 };
760 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
761 && meta.get_generation() == id.get_generation()
762 && (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
763 }
764
765 #[must_use]
776 #[inline(always)]
777 pub fn children_iter(&self, parent: NodeId) -> SceneChildIter<'_> {
778 let idx: usize = parent.as_usize();
779 let valid: bool = self.get_meta().get(idx).is_some_and(|meta: &NodeMeta| {
780 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
781 && meta.get_generation() == parent.get_generation()
782 });
783 if !valid {
784 return SceneChildIter {
785 meta: self.get_meta().as_slice(),
786 topology: self.get_topology().as_slice(),
787 head: NODE_INDEX_NONE,
788 tail: NODE_INDEX_NONE,
789 remaining: 0,
790 };
791 }
792 let topo: NodeTopology = self.get_topology()[idx];
793 SceneChildIter {
794 meta: self.get_meta().as_slice(),
795 topology: self.get_topology().as_slice(),
796 head: topo.get_first_child(),
797 tail: topo.get_last_child(),
798 remaining: topo.get_child_count() as usize,
799 }
800 }
801
802 #[inline]
810 pub fn for_each_child<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
811 where
812 CallbackFn: FnMut(NodeId),
813 {
814 for child_id in self.children_iter(parent) {
815 visit(child_id);
816 }
817 }
818
819 #[inline]
827 pub fn for_each_child_rev<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
828 where
829 CallbackFn: FnMut(NodeId),
830 {
831 for child_id in self.children_iter(parent).rev() {
832 visit(child_id);
833 }
834 }
835
836 #[must_use]
847 #[inline(always)]
848 pub fn child_count(&self, parent: NodeId) -> usize {
849 let idx: usize = parent.as_usize();
850 let Some(meta) = self.get_meta().get(idx) else {
851 return 0;
852 };
853 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
854 || meta.get_generation() != parent.get_generation()
855 {
856 return 0;
857 }
858 self.get_topology()[idx].get_child_count() as usize
859 }
860
861 #[must_use]
872 #[inline(always)]
873 pub fn has_children(&self, parent: NodeId) -> bool {
874 self.child_count(parent) > 0
875 }
876
877 #[must_use]
888 #[inline(always)]
889 pub fn first_child(&self, parent: NodeId) -> Option<NodeId> {
890 let idx: usize = parent.as_usize();
891 let meta: &NodeMeta = self.get_meta().get(idx)?;
892 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
893 || meta.get_generation() != parent.get_generation()
894 {
895 return None;
896 }
897 let first: u32 = self.get_topology()[idx].get_first_child();
898 if first == NODE_INDEX_NONE {
899 None
900 } else {
901 Some(NodeId::new(
902 first,
903 self.get_meta()[first as usize].get_generation(),
904 ))
905 }
906 }
907
908 #[must_use]
919 #[inline(always)]
920 pub fn last_child(&self, parent: NodeId) -> Option<NodeId> {
921 let idx: usize = parent.as_usize();
922 let meta: &NodeMeta = self.get_meta().get(idx)?;
923 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
924 || meta.get_generation() != parent.get_generation()
925 {
926 return None;
927 }
928 let last: u32 = self.get_topology()[idx].get_last_child();
929 if last == NODE_INDEX_NONE {
930 None
931 } else {
932 Some(NodeId::new(
933 last,
934 self.get_meta()[last as usize].get_generation(),
935 ))
936 }
937 }
938
939 #[must_use]
950 #[inline(always)]
951 pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
952 let idx: usize = id.as_usize();
953 let meta: &NodeMeta = self.get_meta().get(idx)?;
954 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
955 {
956 return None;
957 }
958 let next: u32 = self.get_topology()[idx].get_next_sibling();
959 if next == NODE_INDEX_NONE {
960 None
961 } else {
962 Some(NodeId::new(
963 next,
964 self.get_meta()[next as usize].get_generation(),
965 ))
966 }
967 }
968
969 #[must_use]
980 #[inline(always)]
981 pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
982 let idx: usize = id.as_usize();
983 let meta: &NodeMeta = self.get_meta().get(idx)?;
984 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
985 {
986 return None;
987 }
988 let prev: u32 = self.get_topology()[idx].get_prev_sibling();
989 if prev == NODE_INDEX_NONE {
990 None
991 } else {
992 Some(NodeId::new(
993 prev,
994 self.get_meta()[prev as usize].get_generation(),
995 ))
996 }
997 }
998
999 #[must_use]
1010 pub fn children_vec(&self, parent: NodeId) -> Vec<NodeId> {
1011 self.children_iter(parent).collect()
1012 }
1013
1014 #[must_use]
1026 pub fn is_in_subtree(&self, candidate: NodeId, root: NodeId) -> bool {
1027 if candidate == root {
1028 return true;
1029 }
1030 let mut cursor_idx: usize = candidate.as_usize();
1031 let Some(start_meta) = self.get_meta().get(cursor_idx) else {
1032 return false;
1033 };
1034 if (start_meta.get_flags() & NODE_FLAG_ALIVE) == 0
1035 || start_meta.get_generation() != candidate.get_generation()
1036 {
1037 return false;
1038 }
1039 let root_idx: u32 = root.get_index();
1040 let root_gen: u32 = root.get_generation();
1041 let max_hops: usize = self.get_topology().len();
1042 let mut hops: usize = 0;
1043 while hops < max_hops {
1044 let parent_idx: u32 = self.get_topology()[cursor_idx].get_parent();
1045 if parent_idx == NODE_INDEX_NONE {
1046 return false;
1047 }
1048 if parent_idx == root_idx
1049 && self.get_meta()[parent_idx as usize].get_generation() == root_gen
1050 {
1051 return true;
1052 }
1053 cursor_idx = parent_idx as usize;
1054 hops += 1;
1055 }
1056 false
1057 }
1058
1059 fn recompute_nonzero_z_child(&mut self, parent_idx: usize) {
1066 let mut any_nonzero: bool = false;
1067 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1068 while cur != NODE_INDEX_NONE {
1069 let ci: usize = cur as usize;
1070 if self.get_nodes()[ci].layout_ref().get_z_index() != 0 {
1071 any_nonzero = true;
1072 break;
1073 }
1074 cur = self.get_topology()[ci].get_next_sibling();
1075 }
1076 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1077 let next: u16 = if any_nonzero {
1078 meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD
1079 } else {
1080 meta.get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD
1081 };
1082 let _: &mut NodeMeta = meta.set_flags(next);
1083 }
1084 }
1085
1086 fn sync_parent_nonzero_z(&mut self, parent_idx: usize, prev_z: i32, next_z: i32) {
1095 if next_z != 0 {
1096 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1097 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1098 let _: &mut NodeMeta = meta.set_flags(next);
1099 }
1100 } else if prev_z != 0 {
1101 self.recompute_nonzero_z_child(parent_idx);
1102 }
1103 }
1104
1105 fn unlink_child_at(&mut self, parent_idx: usize, child_idx: usize) {
1113 let child_topo: NodeTopology = self.get_topology()[child_idx];
1114 if child_topo.get_parent() != parent_idx as u32 {
1115 return;
1116 }
1117 let prev: u32 = child_topo.get_prev_sibling();
1118 let next: u32 = child_topo.get_next_sibling();
1119 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1120 if prev != NODE_INDEX_NONE {
1121 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(next);
1122 } else {
1123 let _: &mut NodeTopology = topo[parent_idx].set_first_child(next);
1124 }
1125 if next != NODE_INDEX_NONE {
1126 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(prev);
1127 } else {
1128 let _: &mut NodeTopology = topo[parent_idx].set_last_child(prev);
1129 }
1130 let next_count: u32 = topo[parent_idx].get_child_count().saturating_sub(1);
1131 let _: &mut NodeTopology = topo[parent_idx].set_child_count(next_count);
1132 let _: &mut NodeTopology = topo[child_idx]
1133 .set_parent(NODE_INDEX_NONE)
1134 .set_prev_sibling(NODE_INDEX_NONE)
1135 .set_next_sibling(NODE_INDEX_NONE);
1136 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(None);
1137 let child_z: i32 = self.get_nodes()[child_idx].layout_ref().get_z_index();
1138 if child_z != 0 {
1139 self.recompute_nonzero_z_child(parent_idx);
1140 }
1141 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1142 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1143 }
1144
1145 fn link_child_tail_at(&mut self, parent_idx: usize, parent_id: NodeId, child_idx: usize) {
1154 let child_u32: u32 = child_idx as u32;
1155 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1156 let tail: u32 = topo[parent_idx].get_last_child();
1157 let _: &mut NodeTopology = topo[child_idx]
1158 .set_parent(parent_idx as u32)
1159 .set_prev_sibling(tail)
1160 .set_next_sibling(NODE_INDEX_NONE);
1161 if tail != NODE_INDEX_NONE {
1162 let _: &mut NodeTopology = topo[tail as usize].set_next_sibling(child_u32);
1163 } else {
1164 let _: &mut NodeTopology = topo[parent_idx].set_first_child(child_u32);
1165 }
1166 let next_count: u32 = topo[parent_idx].get_child_count().saturating_add(1);
1167 let _: &mut NodeTopology = topo[parent_idx]
1168 .set_last_child(child_u32)
1169 .set_child_count(next_count);
1170 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(Some(parent_id));
1171 if self.get_nodes()[child_idx].layout_ref().get_z_index() != 0 {
1172 let next_flags: u16 =
1173 self.get_meta()[parent_idx].get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1174 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(next_flags);
1175 }
1176 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1177 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1178 }
1179
1180 fn unlink_all_children_at(&mut self, parent_idx: usize) {
1187 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1188 let _: &mut NodeTopology = self.get_mut_topology()[parent_idx]
1189 .set_first_child(NODE_INDEX_NONE)
1190 .set_last_child(NODE_INDEX_NONE)
1191 .set_child_count(0);
1192 let cleared: u16 = self.get_meta()[parent_idx].get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD;
1193 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(cleared);
1194 while cur != NODE_INDEX_NONE {
1195 let ci: usize = cur as usize;
1196 let next: u32 = self.get_topology()[ci].get_next_sibling();
1197 let _: &mut NodeTopology = self.get_mut_topology()[ci]
1198 .set_parent(NODE_INDEX_NONE)
1199 .set_prev_sibling(NODE_INDEX_NONE)
1200 .set_next_sibling(NODE_INDEX_NONE);
1201 let _: &mut SceneNode = self.get_mut_nodes()[ci].set_parent(None);
1202 cur = next;
1203 }
1204 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1205 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1206 }
1207
1208 pub fn set_children_detached(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
1220 if self.get_node(parent).is_none() {
1221 return false;
1222 }
1223 if self.child_count(parent) == new_children.len()
1224 && self.children_iter(parent).eq(new_children.iter().copied())
1225 {
1226 return false;
1227 }
1228 self.clear_subtree_hover(parent);
1229 let parent_idx: usize = parent.as_usize();
1230 self.unlink_all_children_at(parent_idx);
1231 for child in new_children.iter().copied() {
1232 if child == parent || self.get_node(child).is_none() {
1233 continue;
1234 }
1235 let child_idx: usize = child.as_usize();
1236 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1237 if prev_parent != NODE_INDEX_NONE {
1238 self.unlink_child_at(prev_parent as usize, child_idx);
1239 }
1240 self.link_child_tail_at(parent_idx, parent, child_idx);
1241 }
1242 let dirty_lay: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1243 let dirty_child: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
1244 self.mark_dirty(parent, dirty_lay | dirty_child);
1245 true
1246 }
1247
1248 pub fn replace_child(&mut self, parent: NodeId, old_child: NodeId, new_child: NodeId) -> bool {
1261 if old_child == new_child || new_child == parent {
1262 return false;
1263 }
1264 if self.get_node(parent).is_none()
1265 || self.get_node(old_child).is_none()
1266 || self.get_node(new_child).is_none()
1267 {
1268 return false;
1269 }
1270 let parent_idx: usize = parent.as_usize();
1271 let old_idx: usize = old_child.as_usize();
1272 let new_idx: usize = new_child.as_usize();
1273 if self.get_topology()[old_idx].get_parent() != parent_idx as u32 {
1274 return false;
1275 }
1276 self.clear_subtree_hover(old_child);
1277 let prev_parent: u32 = self.get_topology()[new_idx].get_parent();
1278 if prev_parent != NODE_INDEX_NONE {
1279 self.unlink_child_at(prev_parent as usize, new_idx);
1280 }
1281 let old_topo: NodeTopology = self.get_topology()[old_idx];
1282 let prev: u32 = old_topo.get_prev_sibling();
1283 let next: u32 = old_topo.get_next_sibling();
1284 let new_u32: u32 = new_idx as u32;
1285 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1286 if prev != NODE_INDEX_NONE {
1287 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(new_u32);
1288 } else {
1289 let _: &mut NodeTopology = topo[parent_idx].set_first_child(new_u32);
1290 }
1291 if next != NODE_INDEX_NONE {
1292 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(new_u32);
1293 } else {
1294 let _: &mut NodeTopology = topo[parent_idx].set_last_child(new_u32);
1295 }
1296 let _: &mut NodeTopology = topo[new_idx]
1297 .set_parent(parent_idx as u32)
1298 .set_prev_sibling(prev)
1299 .set_next_sibling(next);
1300 let _: &mut NodeTopology = topo[old_idx]
1301 .set_parent(NODE_INDEX_NONE)
1302 .set_prev_sibling(NODE_INDEX_NONE)
1303 .set_next_sibling(NODE_INDEX_NONE);
1304 let _: &mut SceneNode = self.get_mut_nodes()[old_idx].set_parent(None);
1305 let _: &mut SceneNode = self.get_mut_nodes()[new_idx].set_parent(Some(parent));
1306 let old_z: i32 = self.get_nodes()[old_idx].layout_ref().get_z_index();
1307 let new_z: i32 = self.get_nodes()[new_idx].layout_ref().get_z_index();
1308 self.sync_parent_nonzero_z(parent_idx, old_z, new_z);
1309 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1310 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1311 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1312 true
1313 }
1314
1315 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
1327 let is_portal: bool = matches!(kind, NodeKind::Portal)
1328 || style.layout_ref().get_position() == Position::Fixed;
1329 let is_scroll: bool = matches!(kind, NodeKind::ScrollView)
1330 || style.layout_ref().get_overflow() == Overflow::Scroll;
1331 let mut init_flags: u16 = NODE_FLAG_ALIVE;
1332 if is_portal {
1333 init_flags |= NODE_FLAG_IS_PORTAL;
1334 }
1335 if is_scroll {
1336 init_flags |= NODE_FLAG_IS_SCROLL_CONTAINER;
1337 }
1338 let effect_entry: PaintEffectEntry =
1339 PaintEffectEntry::from_paint_and_blur(style.paint_ref(), 0.0);
1340 let effect_id: u32 = self.get_mut_effect_table().insert(effect_entry);
1341 let compact_paint: CompactPaintStyle =
1342 CompactPaintStyle::from_paint(style.paint_ref(), effect_id);
1343 let init_sigs: (u64, u64) = compute_style_sigs(&style);
1344 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
1345 let slot_idx: usize = index as usize;
1346 let slot: &mut SceneNode = &mut self.get_mut_nodes()[slot_idx];
1347 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
1348 *slot = SceneNode::new(next_gen, kind, style);
1349 self.get_mut_meta()[slot_idx] = NodeMeta::new(next_gen, init_flags, DIRTY_ALL);
1350 self.get_mut_topology()[slot_idx] = NodeTopology::default();
1351 self.get_mut_compact_paints()[slot_idx] = compact_paint;
1352 if let Some(ep) = self.get_mut_paint_epochs().get_mut(slot_idx) {
1353 *ep = ep.wrapping_add(1);
1354 }
1355 if let Some(ep) = self.get_mut_node_mutation_epochs().get_mut(slot_idx) {
1356 *ep = ep.wrapping_add(1).max(1);
1357 }
1358 if let Some(sigs) = self.get_mut_style_sigs().get_mut(slot_idx) {
1359 *sigs = init_sigs;
1360 }
1361 NodeId::new(index, next_gen)
1362 } else {
1363 let index: u32 = self.get_nodes().len() as u32;
1364 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
1365 self.get_mut_meta()
1366 .push(NodeMeta::new(1, init_flags, DIRTY_ALL));
1367 self.get_mut_topology().push(NodeTopology::default());
1368 self.get_mut_compact_paints().push(compact_paint);
1369 self.get_mut_paint_epochs().push(0);
1370 self.get_mut_node_mutation_epochs().push(1);
1371 self.get_mut_style_sigs().push(init_sigs);
1372 NodeId::new(index, 1)
1373 };
1374 if is_portal {
1375 self.get_mut_portal_nodes().push(id);
1376 self.set_full_damage_pending(true);
1377 self.clear_dirty_paint_queue();
1378 }
1379 if is_scroll {
1380 self.get_mut_scroll_nodes().push(id);
1381 }
1382 let next_live: usize = self.get_live_count().saturating_add(1);
1383 self.set_live_count(next_live);
1384 let next_created: usize = self.get_created_since_damage().saturating_add(1);
1385 self.set_created_since_damage(next_created);
1386 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1387 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1388 self.set_layout_damage_pending(true);
1389 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
1390 if next_created > DIRTY_PAINT_FULL_THRESHOLD {
1391 self.set_full_damage_pending(true);
1392 self.set_full_damage_overflow(true);
1393 self.clear_dirty_paint_queue();
1394 } else if !self.get_full_damage_pending() {
1395 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1396 self.set_full_damage_pending(true);
1397 self.set_full_damage_overflow(true);
1398 self.clear_dirty_paint_queue();
1399 } else {
1400 self.get_mut_dirty_paint_nodes().push(id);
1401 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1402 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
1403 let _: &mut NodeMeta = meta.set_flags(next_flags);
1404 }
1405 }
1406 }
1407 let next_rev: u64 = self.get_revision().wrapping_add(1);
1408 self.set_revision(next_rev);
1409 notify_frame_needed();
1410 id
1411 }
1412
1413 pub fn create_view(&mut self, style: Style) -> NodeId {
1424 self.create_node(NodeKind::View, style)
1425 }
1426
1427 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
1439 self.create_node(NodeKind::Text(content), style)
1440 }
1441
1442 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1454 self.create_node(NodeKind::Input(state), style)
1455 }
1456
1457 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1469 self.create_node(NodeKind::Image(buffer), style)
1470 }
1471
1472 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
1483 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
1484 }
1485
1486 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
1498 self.create_canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
1499 }
1500
1501 pub fn create_canvas_with_caching(
1514 &mut self,
1515 style: Style,
1516 caching: CanvasCaching,
1517 painter: CanvasDrawCallback,
1518 ) -> NodeId {
1519 let id: NodeId = self.create_node(NodeKind::Canvas(caching), style);
1520 if let Some(node) = self.get_node_mut(id) {
1521 node.set_canvas_painter(Some(painter));
1522 }
1523 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1524 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
1525 let _: &mut NodeMeta = meta.set_flags(next);
1526 }
1527 id
1528 }
1529
1530 pub fn create_portal(&mut self, style: Style) -> NodeId {
1541 self.create_node(NodeKind::Portal, style)
1542 }
1543
1544 pub fn create_fragment(&mut self) -> NodeId {
1554 self.create_node(NodeKind::Fragment, Style::default())
1555 }
1556
1557 #[must_use]
1568 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
1569 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
1570 if node.get_alive() && node.get_generation() == id.get_generation() {
1571 Some(node)
1572 } else {
1573 None
1574 }
1575 }
1576
1577 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
1588 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
1589 if node.get_alive() && node.get_generation() == id.get_generation() {
1590 Some(node)
1591 } else {
1592 None
1593 }
1594 }
1595
1596 #[must_use]
1606 #[inline(always)]
1607 pub fn live_node_count(&self) -> usize {
1608 self.get_live_count()
1609 }
1610
1611 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
1619 if parent == child || self.get_node(parent).is_none() || self.get_node(child).is_none() {
1620 return;
1621 }
1622 let parent_idx: usize = parent.as_usize();
1623 let child_idx: usize = child.as_usize();
1624 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1625 if let Some(old_parent) = prev_parent {
1626 if old_parent != parent {
1627 self.record_subtree_logical_damage(child);
1628 }
1629 self.unlink_child_at(old_parent.as_usize(), child_idx);
1630 if old_parent != parent {
1631 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1632 }
1633 }
1634 self.link_child_tail_at(parent_idx, parent, child_idx);
1635 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1636 }
1637
1638 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
1646 if children.is_empty() || self.get_node(parent).is_none() {
1647 return;
1648 }
1649 let parent_idx: usize = parent.as_usize();
1650 let mut attached_any: bool = false;
1651 for child in children.iter().copied() {
1652 if child == parent || self.get_node(child).is_none() {
1653 continue;
1654 }
1655 let child_idx: usize = child.as_usize();
1656 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1657 if let Some(old_parent) = prev_parent {
1658 if old_parent != parent {
1659 self.record_subtree_logical_damage(child);
1660 }
1661 self.unlink_child_at(old_parent.as_usize(), child_idx);
1662 if old_parent != parent {
1663 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1664 }
1665 }
1666 self.link_child_tail_at(parent_idx, parent, child_idx);
1667 attached_any = true;
1668 }
1669 if attached_any {
1670 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1671 }
1672 }
1673
1674 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
1682 if self.get_node(parent).is_none() {
1683 return;
1684 }
1685 let parent_idx: usize = parent.as_usize();
1686 let old_children: Vec<NodeId> = self.children_vec(parent);
1687 self.unlink_all_children_at(parent_idx);
1688 if new_children.is_empty() {
1689 for old_child in old_children.into_iter() {
1690 self.dispose_subtree(old_child);
1691 }
1692 } else if old_children.len() > 16 && new_children.len() > 16 {
1693 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1694 for old_child in old_children.into_iter() {
1695 if !keep_set.contains(&old_child) {
1696 self.dispose_subtree(old_child);
1697 }
1698 }
1699 } else {
1700 for old_child in old_children.into_iter() {
1701 if !new_children.contains(&old_child) {
1702 self.dispose_subtree(old_child);
1703 }
1704 }
1705 }
1706 for child in new_children.into_iter() {
1707 if child == parent || self.get_node(child).is_none() {
1708 continue;
1709 }
1710 let child_idx: usize = child.as_usize();
1711 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1712 if prev_parent != NODE_INDEX_NONE {
1713 self.unlink_child_at(prev_parent as usize, child_idx);
1714 }
1715 self.link_child_tail_at(parent_idx, parent, child_idx);
1716 }
1717 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1718 }
1719
1720 #[inline]
1731 fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
1732 let same_static: bool = prev.background_color() == next.background_color()
1733 && prev.background_gradient() == next.background_gradient()
1734 && prev.get_border() == next.get_border()
1735 && prev.get_radius() == next.get_radius()
1736 && prev.box_shadow() == next.box_shadow()
1737 && prev.focus_ring_border() == next.focus_ring_border()
1738 && prev.get_cursor() == next.get_cursor()
1739 && prev.get_pointer_events() == next.get_pointer_events();
1740 let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
1741 let composite_changed: bool = prev.get_transform() != next.get_transform()
1742 || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
1743 same_static && same_vis && composite_changed
1744 }
1745
1746 #[inline]
1758 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
1759 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
1760 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
1761 if layout_changed || text_metrics_changed {
1762 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
1763 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
1764 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
1765 Some(next_fixed)
1766 } else {
1767 None
1768 };
1769 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1770 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
1771 let mask: u16 = layout_bits | visual_bits;
1772 return (mask, portal_update);
1773 }
1774 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
1775 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
1776 if paint_changed && !text_visual_changed {
1777 if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
1778 return (DIRTY_COMPOSITE, None);
1779 }
1780 return (DIRTY_PAINT, None);
1781 }
1782 if paint_changed || text_visual_changed {
1783 (DIRTY_PAINT, None)
1784 } else {
1785 (DIRTY_NONE, None)
1786 }
1787 }
1788
1789 #[inline]
1800 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
1801 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
1802 let transform_changed: bool = prev.get_transform() != next.get_transform();
1803 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
1804 let focus_removed: bool =
1805 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
1806 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
1807 let flag_value: bool = shadow_changed || transform_changed;
1808 let is_matched: bool = border_shrank || focus_removed;
1809 let ab: bool = flag_value || is_matched;
1810 ab || opacity_toggled_zero
1811 }
1812
1813 pub fn set_style(&mut self, id: NodeId, style: Style) {
1821 let has_children: bool = self.has_children(id);
1822 let Some(node) = self.get_node(id) else {
1823 return;
1824 };
1825 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
1826 let is_scroll_kind: bool = matches!(node.get_kind(), NodeKind::ScrollView);
1827 let prev: &Style = node.style_ref();
1828 let (dirty_mask, portal_update): (u16, Option<bool>) =
1829 Self::diff_style_change(prev, &style, is_portal_kind);
1830 if dirty_mask == DIRTY_NONE {
1831 return;
1832 }
1833 let prev_scroll: bool =
1834 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1835 let next_scroll: bool =
1836 is_scroll_kind || style.layout_ref().get_overflow() == Overflow::Scroll;
1837 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1838 Some(next_scroll)
1839 } else {
1840 None
1841 };
1842 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
1843 let subtree_hidden: bool = pre_paint
1844 && (prev.paint_ref().get_opacity() > 0.0) != (style.paint_ref().get_opacity() > 0.0)
1845 && has_children;
1846 let prev_z: i32 = prev.layout_ref().get_z_index();
1847 let parent_idx: u32 = self.get_topology()[id.as_usize()].get_parent();
1848 if subtree_hidden {
1849 self.record_subtree_logical_damage(id);
1850 } else if pre_paint {
1851 self.record_node_logical_damage(id);
1852 }
1853 let hiding_now: bool = style.layout_ref().get_display() == Display::None
1854 || style.paint_ref().get_opacity() <= 0.001
1855 || style.paint_ref().get_pointer_events() == PointerEvents::None;
1856 let next_z: i32 = style.layout_ref().get_z_index();
1857 let next_paint: PaintStyle = *style.paint_ref();
1858 if let Some(node) = self.get_node_mut(id) {
1859 node.set_style(style);
1860 }
1861 let blur: f32 = self.backdrop_blur_radius(id);
1862 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1863 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1864 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1865 }
1866 if hiding_now {
1867 self.clear_subtree_hover(id);
1868 }
1869 if let Some(is_portal) = portal_update {
1870 self.sync_portal_registration(id, is_portal);
1871 }
1872 if let Some(is_scroll) = scroll_update {
1873 self.sync_scroll_registration(id, is_scroll);
1874 }
1875 self.mark_dirty(id, dirty_mask);
1876 }
1877
1878 pub fn mutate_style<CallbackFn>(&mut self, id: NodeId, mutator: CallbackFn) -> bool
1890 where
1891 CallbackFn: FnOnce(&mut Style),
1892 {
1893 let has_children: bool = self.has_children(id);
1894 let prev_opt: Option<(Style, bool, bool, u32)> =
1895 self.get_node(id).map(|node: &SceneNode| {
1896 (
1897 *node.style_ref(),
1898 matches!(node.get_kind(), NodeKind::Portal),
1899 matches!(node.get_kind(), NodeKind::ScrollView),
1900 self.get_topology()[id.as_usize()].get_parent(),
1901 )
1902 });
1903 let Some((prev, is_portal_kind, is_scroll_kind, parent_idx)) = prev_opt else {
1904 return false;
1905 };
1906 let mut next: Style = prev;
1907 mutator(&mut next);
1908 let (dirty_mask, portal_update): (u16, Option<bool>) =
1909 Self::diff_style_change(&prev, &next, is_portal_kind);
1910 if dirty_mask == DIRTY_NONE {
1911 return false;
1912 }
1913 let prev_scroll: bool =
1914 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1915 let next_scroll: bool =
1916 is_scroll_kind || next.layout_ref().get_overflow() == Overflow::Scroll;
1917 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1918 Some(next_scroll)
1919 } else {
1920 None
1921 };
1922 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
1923 if pre_paint {
1924 let opacity_toggled_zero: bool =
1925 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
1926 if opacity_toggled_zero && has_children {
1927 self.record_subtree_logical_damage(id);
1928 } else {
1929 self.record_node_logical_damage(id);
1930 }
1931 }
1932 let hiding_now: bool = next.layout_ref().get_display() == Display::None
1933 || next.paint_ref().get_opacity() <= 0.001
1934 || next.paint_ref().get_pointer_events() == PointerEvents::None;
1935 let prev_z: i32 = prev.layout_ref().get_z_index();
1936 let next_z: i32 = next.layout_ref().get_z_index();
1937 let next_paint: PaintStyle = *next.paint_ref();
1938 if let Some(node) = self.get_node_mut(id) {
1939 node.set_style(next);
1940 }
1941 let blur: f32 = self.backdrop_blur_radius(id);
1942 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1943 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1944 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1945 }
1946 if hiding_now {
1947 self.clear_subtree_hover(id);
1948 }
1949 if let Some(is_portal) = portal_update {
1950 self.sync_portal_registration(id, is_portal);
1951 }
1952 if let Some(is_scroll) = scroll_update {
1953 self.sync_scroll_registration(id, is_scroll);
1954 }
1955 self.mark_dirty(id, dirty_mask);
1956 true
1957 }
1958
1959 pub fn set_text(&mut self, id: NodeId, text: String) {
1967 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1968 Some(node) => {
1969 let layout: &LayoutStyle = node.style_ref().layout_ref();
1970 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
1971 && matches!(layout.get_height(), Length::Px(_));
1972 match node.get_mut_kind() {
1973 NodeKind::Text(current) => {
1974 if *current == text {
1975 (false, has_fixed)
1976 } else {
1977 *current = text;
1978 (true, has_fixed)
1979 }
1980 }
1981 _ => (false, false),
1982 }
1983 }
1984 None => (false, false),
1985 };
1986 if changed {
1987 let mask: u16 = if fixed_size {
1988 DIRTY_PAINT
1989 } else {
1990 DIRTY_TEXT_CHANGE_MASK
1991 };
1992 self.mark_dirty(id, mask);
1993 }
1994 }
1995
1996 pub fn set_image(&mut self, id: NodeId, buffer: ImageBuffer) {
2004 let changed: bool = match self.get_node_mut(id) {
2005 Some(node) => {
2006 let same: bool = match node.get_mut_kind() {
2007 NodeKind::Image(existing) => *existing == buffer,
2008 _ => false,
2009 };
2010 if same {
2011 false
2012 } else {
2013 *node.get_mut_kind() = NodeKind::Image(buffer);
2014 true
2015 }
2016 }
2017 None => false,
2018 };
2019 if changed {
2020 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2021 self.mark_dirty(id, dirty_l | DIRTY_PAINT);
2022 notify_frame_needed();
2023 }
2024 }
2025
2026 pub fn set_text_str(&mut self, id: NodeId, text: &str) {
2034 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2035 Some(node) => {
2036 let layout: &LayoutStyle = node.style_ref().layout_ref();
2037 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
2038 && matches!(layout.get_height(), Length::Px(_));
2039 match node.get_mut_kind() {
2040 NodeKind::Text(current) => {
2041 if current.as_str() == text {
2042 (false, has_fixed)
2043 } else {
2044 current.clear();
2045 current.push_str(text);
2046 (true, has_fixed)
2047 }
2048 }
2049 _ => (false, false),
2050 }
2051 }
2052 None => (false, false),
2053 };
2054 if changed {
2055 let mask: u16 = if fixed_size {
2056 DIRTY_PAINT
2057 } else {
2058 DIRTY_TEXT_CHANGE_MASK
2059 };
2060 self.mark_dirty(id, mask);
2061 }
2062 }
2063
2064 pub fn mutate_text<CallbackFn>(&mut self, id: NodeId, mutate: CallbackFn)
2072 where
2073 CallbackFn: FnOnce(&mut String),
2074 {
2075 let (updated, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2076 Some(node) => {
2077 let layout: &LayoutStyle = node.style_ref().layout_ref();
2078 let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
2079 && matches!(layout.get_height(), Length::Px(_));
2080 match node.get_mut_kind() {
2081 NodeKind::Text(current) => {
2082 mutate(current);
2083 (true, has_fixed)
2084 }
2085 _ => (false, false),
2086 }
2087 }
2088 None => (false, false),
2089 };
2090 if updated {
2091 let mask: u16 = if fixed_size {
2092 DIRTY_PAINT
2093 } else {
2094 DIRTY_TEXT_CHANGE_MASK
2095 };
2096 self.mark_dirty(id, mask);
2097 }
2098 }
2099
2100 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
2108 let changed: bool = match self.get_node_mut(id) {
2109 Some(node) => {
2110 let layout_box: LayoutBox = node.get_layout_box();
2111 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
2112 && layout_box.get_content_size().get_height() <= 0.0
2113 && layout_box.get_content_bounds().get_width() <= 0.0
2114 && layout_box.get_content_bounds().get_height() <= 0.0;
2115 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
2116 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
2117 } else {
2118 let max_x: f32 = (layout_box.get_content_size().get_width()
2119 - layout_box.get_content_bounds().get_width())
2120 .max(0.0);
2121 let max_y: f32 = (layout_box.get_content_size().get_height()
2122 - layout_box.get_content_bounds().get_height())
2123 .max(0.0);
2124 Point::new(
2125 offset.get_x().clamp(0.0, max_x),
2126 offset.get_y().clamp(0.0, max_y),
2127 )
2128 };
2129 if layout_box.get_scroll_offset() == clamped {
2130 false
2131 } else {
2132 node.get_mut_layout_box().set_scroll_offset(clamped);
2133 true
2134 }
2135 }
2136 None => false,
2137 };
2138 if changed {
2139 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2140 }
2141 }
2142
2143 pub fn request_scroll_into_view(&mut self, target: NodeId) {
2150 if self.live_generation(target).is_none() {
2151 return;
2152 }
2153 let target_parent: Option<NodeId> = self.get_node(target).and_then(SceneNode::parent_id);
2154 let mut retained: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2155 retained.retain(|existing: &NodeId| {
2156 *existing != target
2157 && self.live_generation(*existing).is_some()
2158 && (target_parent.is_none()
2159 || self.get_node(*existing).and_then(SceneNode::parent_id) != target_parent)
2160 });
2161 retained.push(target);
2162 let _: &mut Self = self.set_pending_scroll_into_view(retained);
2163 self.mark_dirty(target, DIRTY_COMPOSITE);
2164 }
2165
2166 pub fn flush_scroll_into_view_requests(&mut self) -> bool {
2178 if self.get_pending_scroll_into_view().is_empty() {
2179 return false;
2180 }
2181 let requests: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2182 let mut any_scrolled: bool = false;
2183 for target in requests.into_iter() {
2184 if self.live_generation(target).is_none() {
2185 continue;
2186 }
2187 if !self.is_node_visible(target) {
2188 self.get_mut_pending_scroll_into_view().push(target);
2189 continue;
2190 }
2191 let Some(target_node) = self.get_node(target) else {
2192 continue;
2193 };
2194 let target_raw: Rect = target_node.get_layout_box().get_bounds();
2195 if target_raw.get_height() <= 0.0 && target_raw.get_width() <= 0.0 {
2196 self.get_mut_pending_scroll_into_view().push(target);
2197 continue;
2198 }
2199 let mut scroll_ancestor: Option<NodeId> = None;
2200 let mut cursor: Option<NodeId> = target_node.parent_id();
2201 while let Some(parent_id) = cursor {
2202 if let Some(parent_node) = self.get_node(parent_id) {
2203 if matches!(parent_node.get_kind(), NodeKind::ScrollView)
2204 || parent_node.style_ref().layout_ref().get_overflow() == Overflow::Scroll
2205 {
2206 scroll_ancestor = Some(parent_id);
2207 break;
2208 }
2209 cursor = parent_node.parent_id();
2210 } else {
2211 break;
2212 }
2213 }
2214 let Some(scroll_id) = scroll_ancestor else {
2215 continue;
2216 };
2217 let Some(scroll_node) = self.get_node(scroll_id) else {
2218 continue;
2219 };
2220 let scroll_box: LayoutBox = scroll_node.get_layout_box();
2221 let view_rect: Rect = scroll_box.get_content_bounds();
2222 if view_rect.get_height() <= 1.0 {
2223 self.get_mut_pending_scroll_into_view().push(target);
2224 continue;
2225 }
2226 let current_scroll: Point = scroll_box.get_scroll_offset();
2227 let visible_top: f32 = target_raw.get_y() - current_scroll.get_y();
2228 let visible_bottom: f32 = target_raw.bottom() - current_scroll.get_y();
2229 if visible_top < view_rect.get_y() || visible_bottom > view_rect.bottom() {
2230 let offset_in_content: f32 = target_raw.get_y() - view_rect.get_y();
2231 let centered_scroll_y: f32 = offset_in_content
2232 - (view_rect.get_height() - target_raw.get_height()).max(0.0) * 0.5;
2233 let before_offset: Point = current_scroll;
2234 self.set_scroll_offset(
2235 scroll_id,
2236 Point::new(current_scroll.get_x(), centered_scroll_y),
2237 );
2238 let after_offset: Point = self
2239 .get_node(scroll_id)
2240 .map(|node_ref: &SceneNode| node_ref.get_layout_box().get_scroll_offset())
2241 .unwrap_or(before_offset);
2242 if after_offset != before_offset {
2243 any_scrolled = true;
2244 }
2245 }
2246 }
2247 any_scrolled
2248 }
2249
2250 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
2259 let mut changed: bool = false;
2260 let mut prev_metrics: Option<(f32, f32)> = None;
2261 let next_metrics: (f32, f32) = (scroll_y.max(0.0), content_height.max(1.0));
2262 let mut scrollbar_bounds: Option<(Rect, f32, f32)> = None;
2263 if let Some(node) = self.get_node_mut(id) {
2264 let prev: Option<(f32, f32)> = node.virtual_scroll_metrics();
2265 prev_metrics = prev;
2266 let next: Option<(f32, f32)> = Some(next_metrics);
2267 if prev != next {
2268 changed = true;
2269 node.set_virtual_scroll(next);
2270 let raw_b: Rect = node.get_layout_box().get_bounds();
2271 let border_width: f32 = node.style_ref().paint_ref().get_border().get_width();
2272 let view_h: f32 = node
2273 .get_layout_box()
2274 .get_content_bounds()
2275 .get_height()
2276 .max(1.0);
2277 if raw_b.get_width() > 0.0 && raw_b.get_height() > 0.0 {
2278 scrollbar_bounds = Some((raw_b, border_width, view_h));
2279 }
2280 }
2281 }
2282 if changed {
2283 self.bump_node_mutation_epoch(id.as_usize());
2284 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2285 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
2286 let _: &mut NodeMeta = meta.set_flags(next_flags);
2287 }
2288 let show_scrollbar: bool = self
2289 .get_node(self.get_root())
2290 .map(|scene_node: &SceneNode| {
2291 let rb: Rect = scene_node.get_layout_box().get_bounds();
2292 rb.get_width().min(rb.get_height()) >= 540.0
2293 })
2294 .unwrap_or(true);
2295 if !show_scrollbar {
2296 let next_rev: u64 = self.get_revision().wrapping_add(1);
2297 self.set_revision(next_rev);
2298 } else if let Some((raw_b, bloom_width, view_h)) = scrollbar_bounds
2299 && let Some(screen_b) = self.node_screen_bounds(id)
2300 && screen_b.get_width() > 0.0
2301 && screen_b.get_height() > 0.0
2302 {
2303 let inner_y: f32 = screen_b.get_y() + bloom_width;
2304 let inner_h: f32 = (raw_b.get_height() - bloom_width * 2.0).max(1.0);
2305 let track_y: f32 = inner_y + 3.0;
2306 let track_h: f32 = (inner_h - 6.0).max(16.0);
2307 let n_max_sy: f32 = (next_metrics.1 - view_h).max(0.0);
2308 let n_ratio: f32 = (view_h / next_metrics.1.max(view_h)).clamp(0.0, 1.0);
2309 let n_thumb_h: f32 = (track_h * n_ratio).clamp(20.0_f32.min(track_h), track_h);
2310 let n_frac: f32 = if n_max_sy > 1.0 {
2311 (next_metrics.0 / n_max_sy).clamp(0.0, 1.0)
2312 } else {
2313 0.0
2314 };
2315 let ny0: f32 = track_y + (track_h - n_thumb_h) * n_frac;
2316 let ny1: f32 = ny0 + n_thumb_h;
2317 let (y0, y1): (f32, f32) = match prev_metrics {
2318 Some((py, ph)) => {
2319 let p_max_sy: f32 = (ph - view_h).max(0.0);
2320 let p_ratio: f32 = (view_h / ph.max(view_h)).clamp(0.0, 1.0);
2321 let p_thumb_h: f32 =
2322 (track_h * p_ratio).clamp(20.0_f32.min(track_h), track_h);
2323 let p_frac: f32 = if p_max_sy > 1.0 {
2324 (py / p_max_sy).clamp(0.0, 1.0)
2325 } else {
2326 0.0
2327 };
2328 let py0: f32 = track_y + (track_h - p_thumb_h) * p_frac;
2329 let py1: f32 = py0 + p_thumb_h;
2330 (py0.min(ny0) - 4.0, py1.max(ny1) + 4.0)
2331 }
2332 None => (screen_b.get_y(), screen_b.bottom()),
2333 };
2334 let clamped_y0: f32 = y0.max(screen_b.get_y());
2335 let clamped_y1: f32 = y1.min(screen_b.bottom());
2336 let strip_x: f32 = (screen_b.right() - bloom_width - 12.0).max(screen_b.get_x());
2337 let strip_w: f32 = (screen_b.right() - strip_x + 2.0).max(1.0);
2338 let strip_rect: Rect = Rect::new(
2339 strip_x,
2340 clamped_y0,
2341 strip_w,
2342 (clamped_y1 - clamped_y0).max(1.0),
2343 );
2344 if !self.get_full_damage_pending() {
2345 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2346 self.set_full_damage_pending(true);
2347 self.set_full_damage_overflow(true);
2348 self.get_mut_extra_logical_damage().clear();
2349 } else {
2350 self.get_mut_extra_logical_damage().push(strip_rect);
2351 }
2352 }
2353 let next_rev: u64 = self.get_revision().wrapping_add(1);
2354 self.set_revision(next_rev);
2355 } else {
2356 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2357 }
2358 }
2359 }
2360
2361 #[must_use]
2371 pub fn active_webview_node(&self) -> Option<NodeId> {
2372 let Self {
2373 active_webview_node,
2374 ..
2375 } = self;
2376 *active_webview_node
2377 }
2378
2379 pub fn set_active_webview_node(&mut self, node: Option<NodeId>) {
2386 let Self {
2387 active_webview_node,
2388 ..
2389 } = self;
2390 *active_webview_node = node;
2391 }
2392
2393 #[must_use]
2404 pub fn node_effective_opacity(&self, id: NodeId) -> f32 {
2405 let mut combined_alpha: f32 = 1.0;
2406 let mut cursor: Option<NodeId> = Some(id);
2407 while let Some(node_id) = cursor {
2408 let Some(scene_node) = self.get_node(node_id) else {
2409 return 0.0;
2410 };
2411 let style: &Style = scene_node.style_ref();
2412 if style.layout_ref().get_display() == Display::None {
2413 return 0.0;
2414 }
2415 combined_alpha *= style.paint_ref().get_opacity().clamp(0.0, 1.0);
2416 if combined_alpha <= 0.001 {
2417 return 0.0;
2418 }
2419 cursor = scene_node.parent_id();
2420 }
2421 combined_alpha.clamp(0.0, 1.0)
2422 }
2423
2424 #[must_use]
2437 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
2438 let node: &SceneNode = self.get_node(id)?;
2439 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
2440 match self.node_scroll_and_transform(node) {
2441 Some(vals) => vals,
2442 None => return Some(Rect::default()),
2443 };
2444 let raw: Rect = node.get_layout_box().get_bounds();
2445 Some(Rect::new(
2446 raw.get_x() - off.get_x() + tx,
2447 raw.get_y() - off.get_y() + ty,
2448 raw.get_width() * sx,
2449 raw.get_height() * sy,
2450 ))
2451 }
2452
2453 #[inline]
2464 fn node_scroll_and_transform(&self, node: &SceneNode) -> Option<(Point, f32, f32, f32, f32)> {
2465 let style: &Style = node.style_ref();
2466 if style.layout_ref().get_display() == Display::None {
2467 return None;
2468 }
2469 let transform_val: Transform2D = style.paint_ref().get_transform();
2470 let mut tx: f32 = transform_val.get_translate_x();
2471 let mut ty: f32 = transform_val.get_translate_y();
2472 let sx_scale: f32 = transform_val.get_scale_x();
2473 let sy_scale: f32 = transform_val.get_scale_y();
2474 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2475 || style.layout_ref().get_position() == Position::Fixed;
2476 let mut stop_transform: bool = false;
2477 let mut scroll_x: f32 = 0.0;
2478 let mut scroll_y: f32 = 0.0;
2479 let mut cursor: Option<NodeId> = node.parent_id();
2480 while let Some(pid) = cursor {
2481 if let Some(pnode) = self.get_node(pid) {
2482 let pstyle: &Style = pnode.style_ref();
2483 if pstyle.layout_ref().get_display() == Display::None {
2484 return None;
2485 }
2486 if !stop_transform {
2487 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2488 tx += ptr.get_translate_x();
2489 ty += ptr.get_translate_y();
2490 if !start_top_layer {
2491 let off: Point = pnode.get_layout_box().get_scroll_offset();
2492 scroll_x += off.get_x();
2493 scroll_y += off.get_y();
2494 }
2495 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2496 || pstyle.layout_ref().get_position() == Position::Fixed;
2497 if parent_top_layer {
2498 stop_transform = true;
2499 }
2500 }
2501 cursor = pnode.parent_id();
2502 } else {
2503 break;
2504 }
2505 }
2506 Some((Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale))
2507 }
2508
2509 #[must_use]
2522 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
2523 let node: &SceneNode = self.get_node(id)?;
2524 let raw_bounds: Rect = node.get_layout_box().get_bounds();
2525 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
2526 return Some(Rect::default());
2527 }
2528 let style: &Style = node.style_ref();
2529 let paint: &PaintStyle = style.paint_ref();
2530 let transform_val: Transform2D = paint.get_transform();
2531 if transform_val.get_rotation_rad().abs() > 0.0001
2532 || transform_val.get_scale_x() <= 0.0
2533 || transform_val.get_scale_y() <= 0.0
2534 {
2535 return None;
2536 }
2537 let border_w: f32 = paint.get_border().get_width();
2538 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
2539 12.0
2540 } else {
2541 0.0
2542 };
2543 let mut margin: f32 = if border_w > 0.0 {
2544 10.0_f32.max(border_w + 6.0).max(focus_pad)
2545 } else {
2546 4.0_f32.max(focus_pad)
2547 };
2548 if let Some(shadow) = paint.box_shadow() {
2549 let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
2550 let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
2551 let spread: f32 = shadow.get_spread_radius().max(0.0);
2552 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
2553 margin = margin.max(blur_pad + spread + off_max + 4.0);
2554 }
2555 let backdrop_blur: f32 = self.backdrop_blur_radius(id);
2556 if backdrop_blur > 0.0 {
2557 let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
2558 let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
2559 margin = margin.max(blur_halo);
2560 }
2561 let tx: f32 = transform_val.get_translate_x();
2562 let ty: f32 = transform_val.get_translate_y();
2563 let sx: f32 = transform_val.get_scale_x();
2564 let sy: f32 = transform_val.get_scale_y();
2565 let base_rect: Rect = Rect::new(
2566 raw_bounds.get_x() - margin,
2567 raw_bounds.get_y() - margin,
2568 raw_bounds.get_width() + margin * 2.0,
2569 raw_bounds.get_height() + margin * 2.0,
2570 );
2571 let shifted_x: bool = tx != 0.0 || sx != 1.0;
2572 let shifted_y: bool = ty != 0.0 || sy != 1.0;
2573 let mut cur_rect: Rect = if shifted_x || shifted_y {
2574 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
2575 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
2576 let shifted_rect: Rect = Rect::new(
2577 raw_bounds.get_x() + tx - margin - scale_pad_x,
2578 raw_bounds.get_y() + ty - margin - scale_pad_y,
2579 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
2580 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
2581 );
2582 base_rect.union(shifted_rect)
2583 } else {
2584 base_rect
2585 };
2586 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2587 || style.layout_ref().get_position() == Position::Fixed;
2588 let mut cursor: Option<NodeId> = node.parent_id();
2589 while let Some(pid) = cursor {
2590 let Some(pnode) = self.get_node(pid) else {
2591 break;
2592 };
2593 let pstyle: &Style = pnode.style_ref();
2594 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2595 if ptr.get_rotation_rad().abs() > 0.0001
2596 || (ptr.get_scale_x() - 1.0).abs() > 0.001
2597 || (ptr.get_scale_y() - 1.0).abs() > 0.001
2598 {
2599 return None;
2600 }
2601 if !start_top_layer {
2602 let off: Point = pnode.get_layout_box().get_scroll_offset();
2603 cur_rect = Rect::new(
2604 cur_rect.get_x() - off.get_x(),
2605 cur_rect.get_y() - off.get_y(),
2606 cur_rect.get_width(),
2607 cur_rect.get_height(),
2608 );
2609 let p_ov: Overflow = pstyle.layout_ref().get_overflow();
2610 if matches!(p_ov, Overflow::Hidden | Overflow::Scroll) {
2611 let pb: Rect = pnode.get_layout_box().get_bounds();
2612 if pb.get_width() > 0.0 && pb.get_height() > 0.0 {
2613 let clip_box: Rect = Rect::new(
2614 pb.get_x() - 1.0,
2615 pb.get_y() - 1.0,
2616 pb.get_width() + 2.0,
2617 pb.get_height() + 2.0,
2618 );
2619 match cur_rect.intersect(clip_box) {
2620 Some(clipped) => cur_rect = clipped,
2621 None => return Some(Rect::default()),
2622 }
2623 }
2624 }
2625 }
2626 let ptx: f32 = ptr.get_translate_x();
2627 let pty: f32 = ptr.get_translate_y();
2628 if ptx != 0.0 || pty != 0.0 {
2629 cur_rect = Rect::new(
2630 cur_rect.get_x() + ptx,
2631 cur_rect.get_y() + pty,
2632 cur_rect.get_width(),
2633 cur_rect.get_height(),
2634 );
2635 }
2636 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2637 || pstyle.layout_ref().get_position() == Position::Fixed;
2638 if parent_top_layer {
2639 break;
2640 }
2641 cursor = pnode.parent_id();
2642 }
2643 Some(cur_rect)
2644 }
2645
2646 #[must_use]
2657 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
2658 let x0: f32 = (logical.get_x() * scale).floor();
2659 let y0: f32 = (logical.get_y() * scale).floor();
2660 let x1: f32 = (logical.right() * scale).ceil();
2661 let y1: f32 = (logical.bottom() * scale).ceil();
2662 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2663 }
2664
2665 fn record_node_logical_damage(&mut self, id: NodeId) {
2672 if self.get_full_damage_pending() {
2673 return;
2674 }
2675 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
2676 match rect_opt {
2677 Some(rect) => {
2678 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
2679 return;
2680 }
2681 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2682 self.set_full_damage_pending(true);
2683 self.set_full_damage_overflow(true);
2684 self.get_mut_extra_logical_damage().clear();
2685 } else {
2686 self.get_mut_extra_logical_damage().push(rect);
2687 }
2688 }
2689 None => {
2690 self.set_full_damage_pending(true);
2691 }
2692 }
2693 }
2694
2695 fn record_subtree_logical_damage(&mut self, root: NodeId) {
2702 if self.get_full_damage_pending() {
2703 return;
2704 }
2705 let mut stack: Vec<NodeId> = vec![root];
2706 let mut visited: usize = 0;
2707 while let Some(current) = stack.pop() {
2708 let Some(raw_bounds) = self
2709 .get_node(current)
2710 .map(|node: &SceneNode| node.layout_box_ref().get_bounds())
2711 else {
2712 continue;
2713 };
2714 visited += 1;
2715 if visited > DIRTY_PAINT_FULL_THRESHOLD {
2716 self.set_full_damage_pending(true);
2717 self.set_full_damage_overflow(true);
2718 self.get_mut_extra_logical_damage().clear();
2719 return;
2720 }
2721 for child in self.children_iter(current) {
2722 stack.push(child);
2723 }
2724 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
2725 self.record_node_logical_damage(current);
2726 if self.get_full_damage_pending() {
2727 return;
2728 }
2729 }
2730 }
2731 }
2732
2733 pub fn start_transition(&mut self, mut transition: NodeTransition) {
2740 let target: NodeId = transition.get_node();
2741 let had_active: bool = self
2742 .get_transitions()
2743 .iter()
2744 .any(|transform_val: &NodeTransition| transform_val.get_node() == target);
2745 self.get_mut_transitions()
2746 .retain(|object_transform: &NodeTransition| object_transform.get_node() != target);
2747 if had_active && let Some(node) = self.get_node(target) {
2748 let paint: PaintStyle = node.get_style().get_paint();
2749 let transform_val_primary: Transform2D = paint.get_transform();
2750 let cur_op: f32 = paint.get_opacity();
2751 let cur_tx: f32 = transform_val_primary.get_translate_x();
2752 let cur_ty: f32 = transform_val_primary.get_translate_y();
2753 let cur_sc: f32 = transform_val_primary.get_scale_x();
2754 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
2755 .hypot(transition.get_to_ty() - transition.get_from_ty())
2756 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
2757 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
2758 .hypot(transition.get_to_ty() - cur_ty)
2759 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
2760 if full_dist > 0.01 {
2761 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
2762 transition.set_duration((transition.get_duration() * ratio).max(0.05));
2763 }
2764 transition.set_from_opacity(cur_op);
2765 transition.set_from_tx(cur_tx);
2766 transition.set_from_ty(cur_ty);
2767 transition.set_from_scale(cur_sc);
2768 }
2769 self.record_node_logical_damage(target);
2770 let (opacity, transform): (f32, Transform2D) = transition.sample();
2771 let mut unhidden: bool = false;
2772 if let Some(node) = self.get_node_mut(target) {
2773 let style: &mut Style = node.get_mut_style();
2774 if !transition.get_hide_on_complete()
2775 && style.layout_ref().get_display() == Display::None
2776 {
2777 style.get_mut_layout().set_display(Display::Flex);
2778 unhidden = true;
2779 }
2780 style.get_mut_paint().set_opacity(opacity);
2781 style.get_mut_paint().set_transform(transform);
2782 }
2783 if unhidden {
2784 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2785 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2786 } else {
2787 self.mark_dirty(target, DIRTY_COMPOSITE);
2788 }
2789 self.get_mut_transitions().push(transition);
2790 }
2791
2792 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
2803 let len: usize = self.get_transitions().len();
2804 if len == 0 {
2805 return false;
2806 }
2807 let step: f32 = dt_secs.clamp(0.001, 0.05);
2808 let mut any_updated: bool = false;
2809 let mut write_idx: usize = 0;
2810 for read_idx in 0..len {
2811 let target: NodeId = self.get_transitions()[read_idx].get_node();
2812 if self.get_node(target).is_none() {
2813 continue;
2814 }
2815 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
2816 let transform_val: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
2817 let total_span: f32 = transform_val.get_delay() + transform_val.get_duration();
2818 let prev_elapsed: f32 = transform_val.get_elapsed();
2819 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
2820 transform_val.set_elapsed(next_elapsed);
2821 let is_done: bool = transform_val.is_complete();
2822 let in_hold: bool =
2823 prev_elapsed > 0.0 && next_elapsed <= transform_val.get_delay() && !is_done;
2824 if in_hold {
2825 (is_done, None, false)
2826 } else {
2827 let sampled: (f32, Transform2D) = transform_val.sample();
2828 let should_hide: bool = is_done && transform_val.get_hide_on_complete();
2829 (is_done, Some(sampled), should_hide)
2830 }
2831 };
2832 if let Some((opacity, transform)) = sample_opt {
2833 self.record_node_logical_damage(target);
2834 let mut is_portal_hide: bool = false;
2835 if let Some(node) = self.get_node_mut(target) {
2836 is_portal_hide = hide && matches!(node.get_kind(), NodeKind::Portal);
2837 let style: &mut Style = node.get_mut_style();
2838 style.get_mut_paint().set_opacity(opacity);
2839 style.get_mut_paint().set_transform(transform);
2840 if hide {
2841 style.get_mut_layout().set_display(Display::None);
2842 }
2843 }
2844 if hide {
2845 self.clear_subtree_hover(target);
2846 if self
2847 .active_webview_node()
2848 .is_some_and(|webview_id: NodeId| self.is_in_subtree(webview_id, target))
2849 {
2850 self.set_active_webview_node(None);
2851 let _: bool = close_webview_sheet_bridge();
2852 }
2853 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2854 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2855 if is_portal_hide {
2856 self.set_full_damage_pending(true);
2857 self.clear_dirty_paint_queue();
2858 }
2859 } else {
2860 self.mark_dirty(target, DIRTY_COMPOSITE);
2861 }
2862 any_updated = true;
2863 }
2864 if !done {
2865 if write_idx != read_idx {
2866 self.get_mut_transitions().swap(write_idx, read_idx);
2867 }
2868 write_idx += 1;
2869 }
2870 }
2871 self.get_mut_transitions().truncate(write_idx);
2872 any_updated
2873 }
2874
2875 pub fn clear_subtree_hover(&mut self, root: NodeId) {
2882 let hovered_opt: Option<NodeId> = self.get_focus().hovered_node();
2883 if let Some(hovered_id) = hovered_opt
2884 && self.is_in_subtree(hovered_id, root)
2885 {
2886 self.get_mut_focus().set_hovered(None);
2887 let mut walk: Option<NodeId> = Some(hovered_id);
2888 while let Some(cur) = walk {
2889 let mut dirty_paint: bool = false;
2890 let next_parent: Option<NodeId> = if let Some(node) = self.get_node_mut(cur) {
2891 if node.get_interaction().get_hovered() {
2892 node.get_mut_interaction().set_hovered(false);
2893 dirty_paint = node.hover_paint().is_some()
2894 || node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
2895 }
2896 node.parent_id()
2897 } else {
2898 None
2899 };
2900 if dirty_paint {
2901 self.mark_dirty(cur, DIRTY_PAINT);
2902 }
2903 walk = next_parent;
2904 }
2905 }
2906 let pressed_opt: Option<NodeId> = self.get_focus().pressed_node();
2907 if let Some(pressed_id) = pressed_opt
2908 && self.is_in_subtree(pressed_id, root)
2909 {
2910 self.get_mut_focus().set_pressed(None);
2911 if let Some(node) = self.get_node_mut(pressed_id) {
2912 node.get_mut_interaction().set_pressed(false);
2913 }
2914 }
2915 let focused_opt: Option<NodeId> = self.get_focus().focused_node();
2916 if let Some(focused_id) = focused_opt
2917 && self.is_in_subtree(focused_id, root)
2918 {
2919 self.get_mut_focus().set_focused(None);
2920 if let Some(node) = self.get_node_mut(focused_id) {
2921 node.get_mut_interaction().set_focused(false);
2922 }
2923 }
2924 }
2925
2926 #[must_use]
2936 pub fn has_active_transitions(&self) -> bool {
2937 !self.get_transitions().is_empty()
2938 }
2939
2940 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
2948 let attached: bool = if let Some(node) = self.get_node_mut(id) {
2949 node.add_lifecycle(hook);
2950 true
2951 } else {
2952 false
2953 };
2954 if attached {
2955 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2956 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_LIFECYCLE;
2957 let next_flags: u16 = meta.get_flags() | add_flags;
2958 let _: &mut NodeMeta = meta.set_flags(next_flags);
2959 }
2960 let next_lc: usize = self.get_live_lifecycle_count().saturating_add(1);
2961 self.set_live_lifecycle_count(next_lc);
2962 }
2963 }
2964
2965 #[must_use]
2976 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2977 if self.get_live_lifecycle_count() == 0 {
2978 return Vec::new();
2979 }
2980 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
2981 let mut stack: Vec<NodeId> = vec![root];
2982 while let Some(current) = stack.pop() {
2983 let idx: usize = current.as_usize();
2984 let Some(meta) = self.get_meta().get(idx) else {
2985 continue;
2986 };
2987 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
2988 || meta.get_generation() != current.get_generation()
2989 {
2990 continue;
2991 }
2992 if (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0 {
2993 for hook in self.get_nodes()[idx].lifecycle_observers().into_iter() {
2994 out.push((current, hook));
2995 }
2996 }
2997 for child in self.children_iter(current).rev() {
2998 stack.push(child);
2999 }
3000 }
3001 out
3002 }
3003
3004 #[must_use]
3014 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
3015 if self.get_live_lifecycle_count() == 0 {
3016 return Vec::new();
3017 }
3018 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3019 let mut stack: Vec<NodeId> = vec![self.get_root()];
3020 while let Some(current) = stack.pop() {
3021 if let Some(node) = self.get_node(current) {
3022 if node.layout_ref().get_display() == Display::None {
3023 continue;
3024 }
3025 if (self.get_meta()[current.as_usize()].get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
3026 {
3027 for hook in node.lifecycle_observers().into_iter() {
3028 out.push((current, hook));
3029 }
3030 }
3031 for child in self.children_iter(current).rev() {
3032 stack.push(child);
3033 }
3034 }
3035 }
3036 out
3037 }
3038
3039 #[must_use]
3050 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
3051 let mut out: Vec<ScopeId> = Vec::new();
3052 let mut stack: Vec<NodeId> = vec![root];
3053 while let Some(current) = stack.pop() {
3054 let idx: usize = current.as_usize();
3055 let Some(meta) = self.get_meta().get(idx) else {
3056 continue;
3057 };
3058 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
3059 || meta.get_generation() != current.get_generation()
3060 {
3061 continue;
3062 }
3063 if (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
3064 && let Some(scope) = self.get_nodes()[idx].owned_scope()
3065 {
3066 out.push(scope.id());
3067 }
3068 for child in self.children_iter(current).rev() {
3069 stack.push(child);
3070 }
3071 }
3072 out
3073 }
3074
3075 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
3082 if self.get_transitions().is_empty() {
3083 return;
3084 }
3085 let mut ids: HashSet<NodeId> = HashSet::new();
3086 let mut stack: Vec<NodeId> = vec![root];
3087 while let Some(current) = stack.pop() {
3088 if ids.insert(current) && self.get_node(current).is_some() {
3089 for child in self.children_iter(current) {
3090 stack.push(child);
3091 }
3092 }
3093 }
3094 self.get_mut_transitions()
3095 .retain(|transform_val: &NodeTransition| !ids.contains(&transform_val.get_node()));
3096 }
3097
3098 pub fn cancel_node_transitions(&mut self, node_id: NodeId) {
3105 if self.get_transitions().is_empty() {
3106 return;
3107 }
3108 self.get_mut_transitions()
3109 .retain(|transform_val: &NodeTransition| transform_val.get_node() != node_id);
3110 }
3111
3112 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
3120 let attached: bool = if let Some(node) = self.get_node_mut(id) {
3121 if let Some(existing) = node.owned_scope() {
3122 existing.enter(|| {
3123 on_cleanup(move || {
3124 scope.dispose();
3125 });
3126 });
3127 } else {
3128 node.set_scope(Some(scope));
3129 }
3130 true
3131 } else {
3132 false
3133 };
3134 if attached && let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
3135 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_SCOPE;
3136 let next_flags: u16 = meta.get_flags() | add_flags;
3137 let _: &mut NodeMeta = meta.set_flags(next_flags);
3138 }
3139 }
3140
3141 #[must_use]
3152 #[inline(always)]
3153 pub(crate) fn node_paint_epoch(&self, id: NodeId) -> u32 {
3154 self.get_paint_epochs()
3155 .get(id.as_usize())
3156 .copied()
3157 .unwrap_or(0)
3158 }
3159
3160 #[cfg_attr(not(target_arch = "wasm32"), inline)]
3167 pub(crate) fn bump_node_mutation_epoch(&mut self, arena_index: usize) {
3168 if let Some(epoch) = self.get_mut_node_mutation_epochs().get_mut(arena_index) {
3169 *epoch = epoch.wrapping_add(1);
3170 }
3171 }
3172
3173 #[cfg_attr(not(target_arch = "wasm32"), inline)]
3179 pub(crate) fn bump_serial_layout_epoch(&mut self) {
3180 let next_epoch: u64 = self.get_serial_layout_epoch().wrapping_add(1);
3181 self.set_serial_layout_epoch(next_epoch);
3182 }
3183
3184 #[must_use]
3194 #[inline(always)]
3195 pub(crate) fn root_has_layout_dirty(&self) -> bool {
3196 let root_id: NodeId = self.get_root();
3197 self.get_node(root_id).is_some_and(|root_node: &SceneNode| {
3198 root_node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
3199 })
3200 }
3201
3202 fn clear_dirty_paint_queue(&mut self) {
3208 let Self {
3209 dirty_paint_nodes,
3210 meta,
3211 ..
3212 } = self;
3213 for nid in dirty_paint_nodes.drain(..) {
3214 if let Some(slot_meta) = meta.get_mut(nid.as_usize()) {
3215 let next_flags: u16 = slot_meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3216 let _: &mut NodeMeta = slot_meta.set_flags(next_flags);
3217 }
3218 }
3219 }
3220
3221 pub fn mark_dirty(&mut self, id: NodeId, mut mask: u16) {
3229 let node_idx: usize = id.as_usize();
3230 if let Some(cur_sigs) = self
3231 .get_node(id)
3232 .map(|node: &SceneNode| compute_style_sigs(node.style_ref()))
3233 && let Some(slot_sigs) = self.get_mut_style_sigs().get_mut(node_idx)
3234 {
3235 let prev_sigs: (u64, u64) = *slot_sigs;
3236 if cur_sigs != prev_sigs {
3237 *slot_sigs = cur_sigs;
3238 if cur_sigs.0 != prev_sigs.0 {
3239 mask |= DIRTY_LAYOUT | DIRTY_PAINT;
3240 }
3241 if cur_sigs.1 != prev_sigs.1 {
3242 mask |= DIRTY_TEXT | DIRTY_LAYOUT;
3243 mask |= DIRTY_PAINT;
3244 }
3245 }
3246 }
3247 let check_layout_registries: bool = (mask & DIRTY_LAYOUT) != 0;
3248 let (mut parent_opt, portal_state, scroll_state, nonzero_z_state): (
3249 Option<NodeId>,
3250 Option<bool>,
3251 Option<bool>,
3252 Option<bool>,
3253 ) = match self.get_node_mut(id) {
3254 Some(node) => {
3255 node.get_mut_dirty().insert(mask);
3256 let (portal_opt, scroll_opt, nz_z_opt): (Option<bool>, Option<bool>, Option<bool>) =
3257 if check_layout_registries {
3258 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
3259 || node.layout_ref().get_position() == Position::Fixed;
3260 let is_scroll: bool = matches!(node.get_kind(), NodeKind::ScrollView)
3261 || node.layout_ref().get_overflow() == Overflow::Scroll;
3262 let has_nz_z: bool = node.layout_ref().get_z_index() != 0;
3263 (Some(is_portal), Some(is_scroll), Some(has_nz_z))
3264 } else {
3265 (None, None, None)
3266 };
3267 (node.parent_id(), portal_opt, scroll_opt, nz_z_opt)
3268 }
3269 None => return,
3270 };
3271 if (mask & (DIRTY_PAINT | DIRTY_FULL_DAMAGE_MASK)) != 0
3272 && let Some(epoch) = self.get_mut_paint_epochs().get_mut(node_idx)
3273 {
3274 *epoch = epoch.wrapping_add(1);
3275 }
3276 if mask != DIRTY_NONE {
3277 self.bump_node_mutation_epoch(node_idx);
3278 }
3279 let prev_meta_flags: u16 = if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3280 let next_dirty: u16 = meta.get_dirty() | mask;
3281 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3282 meta.get_flags()
3283 } else {
3284 0
3285 };
3286 if let Some(is_portal) = portal_state {
3287 let was_portal: bool = (prev_meta_flags & NODE_FLAG_IS_PORTAL) != 0;
3288 if is_portal != was_portal {
3289 self.sync_portal_registration(id, is_portal);
3290 }
3291 }
3292 if let Some(is_scroll) = scroll_state {
3293 let was_scroll: bool = (prev_meta_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0;
3294 if is_scroll != was_scroll {
3295 self.sync_scroll_registration(id, is_scroll);
3296 }
3297 }
3298 if let Some(has_nz_z) = nonzero_z_state
3299 && let Some(parent_id) = parent_opt
3300 {
3301 let parent_idx: usize = parent_id.as_usize();
3302 if has_nz_z {
3303 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
3304 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
3305 let _: &mut NodeMeta = meta.set_flags(next_flags);
3306 }
3307 } else if self.has_nonzero_z_child(parent_id) {
3308 self.recompute_nonzero_z_child(parent_idx);
3309 }
3310 }
3311 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
3312 self.set_layout_damage_pending(true);
3313 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
3314 }
3315 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3316 if !self.get_full_damage_pending()
3317 && (mask & visual_mask) != 0
3318 && (prev_meta_flags & NODE_FLAG_IN_DIRTY_PAINT_QUEUE) == 0
3319 {
3320 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
3321 self.set_full_damage_pending(true);
3322 self.set_full_damage_overflow(true);
3323 self.clear_dirty_paint_queue();
3324 } else {
3325 self.get_mut_dirty_paint_nodes().push(id);
3326 if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3327 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3328 let _: &mut NodeMeta = meta.set_flags(next_flags);
3329 }
3330 }
3331 }
3332 let mut ancestor_mask: u16 = DIRTY_NONE;
3333 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
3334 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
3335 }
3336 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
3337 ancestor_mask |= DIRTY_SUBTREE_PAINT;
3338 }
3339 if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
3340 ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
3341 }
3342 if ancestor_mask != DIRTY_NONE {
3343 let root_has_mask: bool = {
3344 let root_id: NodeId = self.get_root();
3345 self.get_node(root_id)
3346 .map(|root_node: &SceneNode| {
3347 (root_node.get_dirty().get_bits() & ancestor_mask) == ancestor_mask
3348 })
3349 .unwrap_or(true)
3350 };
3351 let can_early_break: bool = root_has_mask && !self.get_has_stale_hidden_dirty();
3352 while let Some(ancestor_id) = parent_opt {
3353 let ancestor_idx: usize = ancestor_id.as_usize();
3354 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3355 let already: bool =
3356 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
3357 ancestor.get_mut_dirty().insert(ancestor_mask);
3358 parent_opt = ancestor.parent_id();
3359 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3360 let next_dirty: u16 = meta.get_dirty() | ancestor_mask;
3361 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3362 }
3363 if already && can_early_break {
3364 break;
3365 }
3366 } else {
3367 break;
3368 }
3369 }
3370 }
3371 let next_rev: u64 = self.get_revision().wrapping_add(1);
3372 self.set_revision(next_rev);
3373 notify_frame_needed();
3374 }
3375
3376 #[must_use]
3387 pub fn is_node_visible(&self, id: NodeId) -> bool {
3388 let root: NodeId = self.get_root();
3389 let mut cursor: Option<NodeId> = Some(id);
3390 while let Some(cur) = cursor {
3391 let Some(node) = self.get_node(cur) else {
3392 return false;
3393 };
3394 let style: &Style = node.style_ref();
3395 if style.get_layout().get_display() == Display::None
3396 || style.get_paint().get_opacity() <= 0.001
3397 {
3398 return false;
3399 }
3400 if cur == root {
3401 return true;
3402 }
3403 cursor = node.parent_id();
3404 }
3405 false
3406 }
3407
3408 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
3419 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
3420 damage
3421 }
3422
3423 pub(crate) fn collect_surgical_paint_damage(
3435 &mut self,
3436 scale: f32,
3437 allow_partial_layout: bool,
3438 ) -> (DamageRegion, bool) {
3439 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
3440 let layout_pending: bool = self.get_layout_damage_pending();
3441 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
3442 let no_extra: bool = self.get_extra_logical_damage().is_empty();
3443 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
3444 self.set_created_since_damage(0);
3445 self.set_last_collect_composite_only(false);
3446 return (DamageRegion::default(), false);
3447 }
3448 let mut full: bool =
3449 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
3450 let mut saw_paint_or_layout: bool = layout_pending;
3451 let mut saw_composite_or_scroll: bool = false;
3452 let mut region: DamageRegion = DamageRegion::default();
3453 if !full {
3454 let extra_len: usize = self.get_extra_logical_damage().len();
3455 for item_index in 0..extra_len {
3456 let logical_rect: Rect = self.get_extra_logical_damage()[item_index];
3457 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
3458 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3459 }
3460 }
3461 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3462 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3463 for outer_index in 0..dirty_len {
3464 let nid: NodeId = self.get_dirty_paint_nodes()[outer_index];
3465 let Some(node) = self.get_node(nid) else {
3466 continue;
3467 };
3468 let bits: u16 = node.get_dirty().get_bits();
3469 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
3470 if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
3471 saw_paint_or_layout = true;
3472 }
3473 if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
3474 saw_composite_or_scroll = true;
3475 }
3476 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
3477 full = true;
3478 break;
3479 }
3480 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
3481 full = true;
3482 break;
3483 }
3484 if (bits & visual_mask) == 0 {
3485 continue;
3486 }
3487 let raw_bounds: Rect = node.get_layout_box().get_bounds();
3488 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
3489 match self.node_conservative_logical_rect(nid) {
3490 Some(logical_rect) => {
3491 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3492 }
3493 None => {
3494 full = true;
3495 break;
3496 }
3497 }
3498 } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
3499 && !has_layout_bits
3500 && node.style_ref().layout_ref().get_display() != Display::None
3501 {
3502 full = true;
3503 break;
3504 }
3505 }
3506 }
3507 self.set_last_collect_composite_only(
3508 !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
3509 );
3510 self.set_layout_damage_pending(false);
3511 self.set_created_since_damage(0);
3512 self.get_mut_extra_logical_damage().clear();
3513 if !full {
3514 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3515 let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
3516 for step_index in 0..dirty_len {
3517 let nid: NodeId = self.get_dirty_paint_nodes()[step_index];
3518 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
3519 Some(node) => {
3520 node.get_mut_dirty().remove(clear_mask);
3521 node.parent_id()
3522 }
3523 None => None,
3524 };
3525 if let Some(meta) = self.get_mut_meta().get_mut(nid.get_index() as usize) {
3526 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3527 let next_flags: u16 = meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3528 let _: &mut NodeMeta = meta.set_dirty(next_dirty).set_flags(next_flags);
3529 }
3530 while let Some(ancestor_id) = parent_opt {
3531 let ancestor_idx: usize = ancestor_id.get_index() as usize;
3532 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3533 if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
3534 break;
3535 }
3536 ancestor.get_mut_dirty().remove(ancestor_clear);
3537 parent_opt = ancestor.parent_id();
3538 } else {
3539 break;
3540 }
3541 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3542 let next_dirty: u16 = meta.get_dirty() & !ancestor_clear;
3543 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3544 }
3545 }
3546 }
3547 self.get_mut_dirty_paint_nodes().clear();
3548 return (region, layout_pending);
3549 }
3550 self.set_full_damage_pending(false);
3551 self.clear_dirty_paint_queue();
3552 let node_count: usize = self.get_nodes().len();
3553 for idx in 0..node_count {
3554 let should_clear: bool = {
3555 let node: &SceneNode = &self.get_nodes()[idx];
3556 node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0
3557 };
3558 if should_clear {
3559 self.get_mut_nodes()[idx].get_mut_dirty().remove(clear_mask);
3560 if let Some(meta) = self.get_mut_meta().get_mut(idx) {
3561 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3562 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3563 }
3564 }
3565 }
3566 (DamageRegion::full(), layout_pending)
3567 }
3568
3569 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
3579 let was_overflow: bool = self.get_full_damage_overflow();
3580 self.set_full_damage_overflow(false);
3581 was_overflow
3582 }
3583
3584 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
3595 if id == self.get_root() || self.get_node(id).is_none() {
3596 return (Vec::new(), Vec::new());
3597 }
3598 self.record_subtree_logical_damage(id);
3599 self.cancel_subtree_transitions(id);
3600 self.clear_subtree_hover(id);
3601 let root_parent: u32 = self.get_topology()[id.as_usize()].get_parent();
3602 if root_parent != NODE_INDEX_NONE {
3603 self.unlink_child_at(root_parent as usize, id.as_usize());
3604 }
3605 let mut stack: Vec<NodeId> = vec![id];
3606 let mut scopes: Vec<Scope> = Vec::new();
3607 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3608 while let Some(current) = stack.pop() {
3609 let cur_idx: usize = current.as_usize();
3610 let mut next_child: u32 = self.get_topology()[cur_idx].get_first_child();
3611 let mut removed_lifecycles: usize = 0;
3612 let (was_alive, prev_flags): (bool, u16) = match self.get_node_mut(current) {
3613 Some(node) => {
3614 node.set_alive(false);
3615 node.set_kind(NodeKind::View);
3616 if node.has_extras() {
3617 if let Some(scope) = node.owned_scope() {
3618 scopes.push(scope);
3619 }
3620 let drained: Vec<Rc<dyn Lifecycle>> = node.take_lifecycles();
3621 removed_lifecycles = drained.len();
3622 for hook in drained.into_iter() {
3623 observers.push((current, hook));
3624 }
3625 node.clear_extras();
3626 }
3627 node.set_parent(None);
3628 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
3629 node.set_generation(next_gen);
3630 (true, self.get_meta()[cur_idx].get_flags())
3631 }
3632 None => (false, 0),
3633 };
3634 if !was_alive {
3635 continue;
3636 }
3637 while next_child != NODE_INDEX_NONE {
3638 let ci: usize = next_child as usize;
3639 let sibling: u32 = self.get_topology()[ci].get_next_sibling();
3640 let child_gen: u32 = self.get_meta()[ci].get_generation();
3641 stack.push(NodeId::new(next_child, child_gen));
3642 next_child = sibling;
3643 }
3644 let next_gen: u32 = self.get_nodes()[cur_idx].get_generation();
3645 self.get_mut_meta()[cur_idx] = NodeMeta::new(next_gen, 0, DIRTY_NONE);
3646 self.get_mut_topology()[cur_idx] = NodeTopology::default();
3647 let prev_effect_id: u32 = self.get_compact_paints()[cur_idx].get_effect_id();
3648 if prev_effect_id != EFFECT_ID_NONE {
3649 self.get_mut_effect_table().remove(prev_effect_id);
3650 let _: &mut CompactPaintStyle =
3651 self.get_mut_compact_paints()[cur_idx].set_effect_id(EFFECT_ID_NONE);
3652 }
3653 let next_live: usize = self.get_live_count().saturating_sub(1);
3654 self.set_live_count(next_live);
3655 if removed_lifecycles > 0 {
3656 let next_lc: usize = self
3657 .get_live_lifecycle_count()
3658 .saturating_sub(removed_lifecycles);
3659 self.set_live_lifecycle_count(next_lc);
3660 }
3661 if (prev_flags & NODE_FLAG_IS_PORTAL) != 0 && !self.portal_nodes().is_empty() {
3662 self.sync_portal_registration(current, false);
3663 }
3664 if (prev_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0 && !self.scroll_nodes().is_empty()
3665 {
3666 self.sync_scroll_registration(current, false);
3667 }
3668 if !self.get_backdrop_blur_nodes().is_empty() {
3669 self.get_mut_backdrop_blur_nodes()
3670 .retain(|entry: &(NodeId, f32)| entry.0 != current);
3671 }
3672 if self.active_webview_node() == Some(current) {
3673 self.set_active_webview_node(None);
3674 let _: bool = close_webview_sheet_bridge();
3675 }
3676 if self.get_focus().focused_node() == Some(current) {
3677 self.get_mut_focus().set_focused(None);
3678 }
3679 if self.get_focus().hovered_node() == Some(current) {
3680 self.get_mut_focus().set_hovered(None);
3681 }
3682 if self.get_focus().pressed_node() == Some(current) {
3683 self.get_mut_focus().set_pressed(None);
3684 }
3685 let sel_hits_current: bool =
3686 self.text_selection().is_some_and(|sel: SelectionState| {
3687 sel.get_anchor_node() == current || sel.get_focus_node() == current
3688 }) || self
3689 .text_selection_spans_ref()
3690 .iter()
3691 .any(|&(nid, _, _): &(NodeId, usize, usize)| nid == current);
3692 if sel_hits_current {
3693 self.set_text_selection(None);
3694 }
3695 self.get_mut_free_list().push(current.get_index());
3696 }
3697 (scopes, observers)
3698 }
3699
3700 pub fn dispose_subtree(&mut self, id: NodeId) {
3707 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
3708 finalize_disposed_subtree(scopes, observers);
3709 }
3710
3711 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
3722 let prev: Option<NodeId> = self.get_focus().focused_node();
3723 if prev == target {
3724 return Vec::new();
3725 }
3726 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
3727 if let Some(old_id) = prev {
3728 if let Some(old_node) = self.get_node_mut(old_id) {
3729 old_node.get_mut_interaction().set_focused(false);
3730 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
3731 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
3732 }
3733 }
3734 self.mark_dirty(old_id, DIRTY_PAINT);
3735 }
3736 self.get_mut_focus().set_focused(target);
3737 if let Some(new_id) = target {
3738 if let Some(new_node) = self.get_node_mut(new_id) {
3739 new_node.get_mut_interaction().set_focused(true);
3740 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
3741 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
3742 }
3743 }
3744 self.mark_dirty(new_id, DIRTY_PAINT);
3745 }
3746 callbacks
3747 }
3748
3749 #[must_use]
3760 pub fn effective_text_select_mode(&self, id: NodeId) -> TextSelectMode {
3761 let mut cursor: Option<NodeId> = Some(id);
3762 while let Some(cur) = cursor {
3763 let Some(node) = self.get_node(cur) else {
3764 return TextSelectMode::None;
3765 };
3766 if let Some(mode) = node.style_ref().text_ref().text_select_mode() {
3767 return mode;
3768 }
3769 cursor = node.parent_id();
3770 }
3771 TextSelectMode::None
3772 }
3773
3774 #[must_use]
3785 pub fn is_node_selectable(&self, id: NodeId) -> bool {
3786 self.effective_text_select_mode(id) != TextSelectMode::None
3787 }
3788
3789 #[must_use]
3800 pub(crate) fn selectable_scope_root(&self, id: NodeId) -> Option<(NodeId, TextSelectMode)> {
3801 let target_mode: TextSelectMode = self.effective_text_select_mode(id);
3802 if target_mode == TextSelectMode::None {
3803 return None;
3804 }
3805 let mut scope: NodeId = id;
3806 loop {
3807 let cur_node: &SceneNode = self.get_node(scope)?;
3808 if matches!(cur_node.get_kind(), NodeKind::Portal) {
3809 break;
3810 }
3811 let Some(parent_id) = cur_node.parent_id() else {
3812 break;
3813 };
3814 if self.effective_text_select_mode(parent_id) != target_mode {
3815 break;
3816 }
3817 scope = parent_id;
3818 }
3819 Some((scope, target_mode))
3820 }
3821
3822 #[must_use]
3833 pub(crate) fn selectable_scope_text_nodes(&self, id: NodeId) -> Vec<NodeId> {
3834 let Some((scope_root, target_mode)) = self.selectable_scope_root(id) else {
3835 return Vec::new();
3836 };
3837 let mut out: Vec<NodeId> = Vec::new();
3838 let mut stack: Vec<NodeId> = vec![scope_root];
3839 while let Some(cid) = stack.pop() {
3840 let Some(node) = self.get_node(cid) else {
3841 continue;
3842 };
3843 if !node.get_alive() || node.style_ref().get_layout().get_display() == Display::None {
3844 continue;
3845 }
3846 if cid != scope_root {
3847 if matches!(node.get_kind(), NodeKind::Portal) {
3848 continue;
3849 }
3850 if node
3851 .style_ref()
3852 .text_ref()
3853 .text_select_mode()
3854 .is_some_and(|matrix_elems: TextSelectMode| matrix_elems != target_mode)
3855 {
3856 continue;
3857 }
3858 }
3859 if matches!(node.get_kind(), NodeKind::Text(_)) {
3860 out.push(cid);
3861 } else {
3862 let start_len: usize = stack.len();
3863 stack.extend(self.children_iter(cid));
3864 stack[start_len..].reverse();
3865 }
3866 }
3867 out
3868 }
3869
3870 #[must_use]
3881 pub(crate) fn text_node_screen_content_rect(&self, node_id: NodeId) -> Option<Rect> {
3882 let node: &SceneNode = self.get_node(node_id)?;
3883 let computed_box: LayoutBox = node.get_layout_box();
3884 let outer: Rect = computed_box.get_bounds();
3885 let content_rect: Rect = computed_box.get_content_bounds();
3886 let screen_outer: Rect = self.node_screen_bounds(node_id).unwrap_or(outer);
3887 Some(Rect::new(
3888 screen_outer.get_x() + (content_rect.get_x() - outer.get_x()),
3889 screen_outer.get_y() + (content_rect.get_y() - outer.get_y()),
3890 content_rect.get_width(),
3891 content_rect.get_height(),
3892 ))
3893 }
3894
3895 #[must_use]
3907 fn is_new_visual_row(&self, prev_id: NodeId, cur_id: NodeId) -> bool {
3908 let prev_rect: Option<Rect> = self.text_node_screen_content_rect(prev_id);
3909 let cur_rect: Option<Rect> = self.text_node_screen_content_rect(cur_id);
3910 if let (Some(pr), Some(cr)) = (prev_rect, cur_rect)
3911 && pr.get_height() > 0.0
3912 && cr.get_height() > 0.0
3913 {
3914 let prev_cy: f32 = pr.get_y() + pr.get_height() * 0.5;
3915 let cur_cy: f32 = cr.get_y() + cr.get_height() * 0.5;
3916 let threshold: f32 = (pr.get_height().min(cr.get_height()) * 0.5).max(4.0);
3917 return (cur_cy - prev_cy).abs() > threshold;
3918 }
3919 let prev_parent: Option<NodeId> = self.get_node(prev_id).and_then(SceneNode::parent_id);
3920 let cur_parent: Option<NodeId> = self.get_node(cur_id).and_then(SceneNode::parent_id);
3921 if let (Some(pp), Some(cp)) = (prev_parent, cur_parent)
3922 && pp == cp
3923 && let Some(pnode) = self.get_node(pp)
3924 && pnode.style_ref().get_layout().get_flex_direction() == FlexDirection::Row
3925 {
3926 return false;
3927 }
3928 true
3929 }
3930
3931 #[must_use]
3942 fn resolve_selection_spans(&self, selection: SelectionState) -> Vec<(NodeId, usize, usize)> {
3943 if selection.is_empty() {
3944 return Vec::new();
3945 }
3946 if selection.is_single_node() {
3947 let nid: NodeId = selection.get_anchor_node();
3948 let Some(node) = self.get_node(nid) else {
3949 return Vec::new();
3950 };
3951 let NodeKind::Text(content) = node.get_kind() else {
3952 return Vec::new();
3953 };
3954 let len: usize = content.chars().count();
3955 let (raw_s, raw_e): (usize, usize) = selection.ordered_range();
3956 let start_c: usize = raw_s.min(len);
3957 let end_c: usize = raw_e.min(len);
3958 return if start_c < end_c {
3959 vec![(nid, start_c, end_c)]
3960 } else {
3961 Vec::new()
3962 };
3963 }
3964 let anchor_id: NodeId = selection.get_anchor_node();
3965 let focus_id: NodeId = selection.get_focus_node();
3966 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_id);
3967 let anchor_pos: Option<usize> = nodes
3968 .iter()
3969 .position(|target_node_id: &NodeId| *target_node_id == anchor_id);
3970 let focus_pos: Option<usize> = nodes
3971 .iter()
3972 .position(|element_id: &NodeId| *element_id == focus_id);
3973 let (Some(a_pos), Some(f_pos)) = (anchor_pos, focus_pos) else {
3974 return Vec::new();
3975 };
3976 let (start_pos, start_ch, end_pos, end_ch): (usize, usize, usize, usize) = if a_pos <= f_pos
3977 {
3978 (
3979 a_pos,
3980 selection.get_anchor_char(),
3981 f_pos,
3982 selection.get_focus_char(),
3983 )
3984 } else {
3985 (
3986 f_pos,
3987 selection.get_focus_char(),
3988 a_pos,
3989 selection.get_anchor_char(),
3990 )
3991 };
3992 let mut spans: Vec<(NodeId, usize, usize)> =
3993 Vec::with_capacity(end_pos.saturating_sub(start_pos) + 1);
3994 for (idx, &nid) in nodes.iter().enumerate().take(end_pos + 1).skip(start_pos) {
3995 let Some(node) = self.get_node(nid) else {
3996 continue;
3997 };
3998 let NodeKind::Text(content) = node.get_kind() else {
3999 continue;
4000 };
4001 let len: usize = content.chars().count();
4002 let source_val: usize = if idx == start_pos {
4003 start_ch.min(len)
4004 } else {
4005 0
4006 };
4007 let event_ref: usize = if idx == end_pos { end_ch.min(len) } else { len };
4008 if source_val < event_ref || (idx > start_pos && idx < end_pos) {
4009 spans.push((nid, source_val, event_ref));
4010 }
4011 }
4012 spans
4013 }
4014
4015 #[must_use]
4025 pub(crate) fn text_selection_spans_ref(&self) -> &[(NodeId, usize, usize)] {
4026 let Self {
4027 text_selection_spans,
4028 ..
4029 } = self;
4030 text_selection_spans.as_slice()
4031 }
4032
4033 #[must_use]
4044 pub(crate) fn text_selection_range_for(&self, id: NodeId) -> Option<(usize, usize)> {
4045 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4046 if spans.is_empty() {
4047 return None;
4048 }
4049 for &(nid, source_val, event_ref) in spans.iter() {
4050 if nid == id {
4051 return if source_val < event_ref {
4052 Some((source_val, event_ref))
4053 } else {
4054 None
4055 };
4056 }
4057 }
4058 None
4059 }
4060
4061 #[must_use]
4073 pub(crate) fn is_descendant_of(&self, id: NodeId, ancestor: NodeId) -> bool {
4074 let mut cursor: Option<NodeId> = Some(id);
4075 while let Some(cur) = cursor {
4076 if cur == ancestor {
4077 return true;
4078 }
4079 cursor = self.get_node(cur).and_then(SceneNode::parent_id);
4080 }
4081 false
4082 }
4083
4084 #[must_use]
4095 pub fn effective_selection_color(&self, id: NodeId) -> Color {
4096 let mut cursor: Option<NodeId> = Some(id);
4097 while let Some(cur) = cursor {
4098 let Some(node) = self.get_node(cur) else {
4099 break;
4100 };
4101 if let Some(color) = node.style_ref().text_ref().selection_color() {
4102 return color;
4103 }
4104 cursor = node.parent_id();
4105 }
4106 DEFAULT_TEXT_SELECTION_COLOR
4107 }
4108
4109 #[must_use]
4119 pub fn text_selection(&self) -> Option<SelectionState> {
4120 let Self { text_selection, .. } = self;
4121 *text_selection
4122 }
4123
4124 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
4131 let prev: Option<SelectionState> = self.text_selection();
4132 if prev == selection {
4133 return;
4134 }
4135 let mut dirty_ids: Vec<NodeId> =
4136 Vec::with_capacity(self.text_selection_spans_ref().len() + 4);
4137 for &(nid, _, _) in self.text_selection_spans_ref().iter() {
4138 dirty_ids.push(nid);
4139 }
4140 if let Some(old_sel) = prev {
4141 dirty_ids.push(old_sel.get_anchor_node());
4142 if !old_sel.is_single_node() {
4143 dirty_ids.push(old_sel.get_focus_node());
4144 }
4145 }
4146 let next_spans: Vec<(NodeId, usize, usize)> = selection
4147 .map(|sel: SelectionState| self.resolve_selection_spans(sel))
4148 .unwrap_or_default();
4149 for &(nid, _, _) in next_spans.iter() {
4150 dirty_ids.push(nid);
4151 }
4152 if let Some(new_sel) = selection {
4153 dirty_ids.push(new_sel.get_anchor_node());
4154 if !new_sel.is_single_node() {
4155 dirty_ids.push(new_sel.get_focus_node());
4156 }
4157 }
4158 let Self {
4159 text_selection,
4160 text_selection_spans,
4161 ..
4162 } = self;
4163 *text_selection = selection;
4164 *text_selection_spans = next_spans;
4165 for nid in dirty_ids.into_iter() {
4166 self.mark_dirty(nid, DIRTY_PAINT);
4167 }
4168 }
4169
4170 pub fn clear_text_selection(&mut self) {
4176 self.set_text_selection(None);
4177 }
4178
4179 #[must_use]
4190 fn extract_selected_text_filtered(&self, container: Option<NodeId>) -> Option<String> {
4191 let sel: SelectionState = self.text_selection()?;
4192 if sel.is_empty() {
4193 return None;
4194 }
4195 if let Some(root) = container
4196 && !self.is_descendant_of(sel.get_anchor_node(), root)
4197 {
4198 return None;
4199 }
4200 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4201 if spans.is_empty() {
4202 return None;
4203 }
4204 if spans.len() == 1 {
4205 let (nid, source_val, event_ref): (NodeId, usize, usize) = spans[0];
4206 if let Some(root) = container
4207 && !self.is_descendant_of(nid, root)
4208 {
4209 return None;
4210 }
4211 let node: &SceneNode = self.get_node(nid)?;
4212 let NodeKind::Text(content) = node.get_kind() else {
4213 return None;
4214 };
4215 let extracted: &str = extract_char_range(content.as_str(), source_val, event_ref);
4216 return if extracted.is_empty() {
4217 None
4218 } else {
4219 Some(extracted.to_string())
4220 };
4221 }
4222 let mut out: String = String::new();
4223 let mut prev_emitted_node: Option<NodeId> = None;
4224 let last_span_idx: usize = spans.len().saturating_sub(1);
4225 for (idx, &(nid, scale_val, error_val)) in spans.iter().enumerate() {
4226 if let Some(root) = container
4227 && !self.is_descendant_of(nid, root)
4228 {
4229 continue;
4230 }
4231 let Some(node) = self.get_node(nid) else {
4232 continue;
4233 };
4234 let NodeKind::Text(content) = node.get_kind() else {
4235 continue;
4236 };
4237 let part: &str = extract_char_range(content.as_str(), scale_val, error_val);
4238 let is_middle_empty: bool = part.is_empty() && idx > 0 && idx < last_span_idx;
4239 if part.is_empty() && !is_middle_empty {
4240 continue;
4241 }
4242 if let Some(prev_id) = prev_emitted_node
4243 && self.is_new_visual_row(prev_id, nid)
4244 {
4245 out.push('\n');
4246 }
4247 out.push_str(part);
4248 prev_emitted_node = Some(nid);
4249 }
4250 if out.is_empty() { None } else { Some(out) }
4251 }
4252
4253 #[must_use]
4263 pub fn get_selected_text(&self) -> Option<String> {
4264 if let Some(sel) = self.extract_selected_text_filtered(None) {
4265 return Some(sel);
4266 }
4267 let focused: NodeId = self.get_focus().focused_node()?;
4268 let node: &SceneNode = self.get_node(focused)?;
4269 if let NodeKind::Input(state) = node.get_kind() {
4270 return state.selected_text().map(str::to_string);
4271 }
4272 None
4273 }
4274
4275 #[must_use]
4286 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4287 self.extract_selected_text_filtered(Some(container))
4288 }
4289
4290 pub fn select_all_text(&mut self, id: NodeId) -> bool {
4301 if !self.is_node_selectable(id) {
4302 return false;
4303 }
4304 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4305 let Some(&first_id) = nodes.first() else {
4306 return false;
4307 };
4308 let Some(&last_id) = nodes.last() else {
4309 return false;
4310 };
4311 let last_len: usize = self
4312 .get_node(last_id)
4313 .and_then(|node: &SceneNode| {
4314 if let NodeKind::Text(content) = node.get_kind() {
4315 Some(content.chars().count())
4316 } else {
4317 None
4318 }
4319 })
4320 .unwrap_or(0);
4321 if nodes.len() == 1 && last_len == 0 {
4322 return false;
4323 }
4324 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4325 true
4326 }
4327
4328 pub(crate) fn select_line_text(&mut self, id: NodeId) -> bool {
4339 if !self.is_node_selectable(id) {
4340 return false;
4341 }
4342 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4343 let Some(pos) = nodes
4344 .iter()
4345 .position(|target_node_id: &NodeId| *target_node_id == id)
4346 else {
4347 return false;
4348 };
4349 let mut start_idx: usize = pos;
4350 while start_idx > 0 && !self.is_new_visual_row(nodes[start_idx - 1], id) {
4351 start_idx -= 1;
4352 }
4353 let mut end_idx: usize = pos;
4354 while end_idx + 1 < nodes.len() && !self.is_new_visual_row(id, nodes[end_idx + 1]) {
4355 end_idx += 1;
4356 }
4357 let first_id: NodeId = nodes[start_idx];
4358 let last_id: NodeId = nodes[end_idx];
4359 let last_len: usize = self
4360 .get_node(last_id)
4361 .and_then(|node: &SceneNode| {
4362 if let NodeKind::Text(content) = node.get_kind() {
4363 Some(content.chars().count())
4364 } else {
4365 None
4366 }
4367 })
4368 .unwrap_or(0);
4369 if first_id == last_id && last_len == 0 {
4370 return false;
4371 }
4372 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4373 true
4374 }
4375
4376 #[must_use]
4388 pub(crate) fn hit_test_selectable_scope(
4389 &self,
4390 anchor_or_hit: NodeId,
4391 pos: Point,
4392 ) -> Option<(NodeId, usize)> {
4393 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_or_hit);
4394 if nodes.is_empty() {
4395 return None;
4396 }
4397 let mut rects: Vec<(NodeId, Rect, TextStyle, usize)> = Vec::with_capacity(nodes.len());
4398 let mut overall_min_y: f32 = f32::INFINITY;
4399 let mut overall_max_y: f32 = f32::NEG_INFINITY;
4400 for &nid in nodes.iter() {
4401 let Some(node) = self.get_node(nid) else {
4402 continue;
4403 };
4404 let NodeKind::Text(content) = node.get_kind() else {
4405 continue;
4406 };
4407 let Some(rect) = self.text_node_screen_content_rect(nid) else {
4408 continue;
4409 };
4410 let tstyle: TextStyle = node.get_style().get_text();
4411 if pos.get_x() >= rect.get_x()
4412 && pos.get_x() <= rect.right()
4413 && pos.get_y() >= rect.get_y()
4414 && pos.get_y() <= rect.bottom()
4415 {
4416 let ch: usize = hit_test_text_char(content.as_str(), tstyle, rect, pos);
4417 return Some((nid, ch));
4418 }
4419 if rect.get_y() < overall_min_y {
4420 overall_min_y = rect.get_y();
4421 }
4422 if rect.bottom() > overall_max_y {
4423 overall_max_y = rect.bottom();
4424 }
4425 rects.push((nid, rect, tstyle, content.chars().count()));
4426 }
4427 if rects.is_empty() {
4428 return None;
4429 }
4430 if pos.get_y() < overall_min_y - 4.0 {
4431 return Some((rects[0].0, 0));
4432 }
4433 if pos.get_y() > overall_max_y + 4.0 {
4434 let last: (NodeId, Rect, TextStyle, usize) = rects[rects.len() - 1];
4435 return Some((last.0, last.3));
4436 }
4437 let mut min_dy: f32 = f32::INFINITY;
4438 for &(_, rect, _, _) in rects.iter() {
4439 let dy: f32 = if pos.get_y() < rect.get_y() {
4440 rect.get_y() - pos.get_y()
4441 } else if pos.get_y() > rect.bottom() {
4442 pos.get_y() - rect.bottom()
4443 } else {
4444 0.0
4445 };
4446 if dy < min_dy {
4447 min_dy = dy;
4448 }
4449 }
4450 let mut best: Option<(NodeId, Rect, TextStyle, f32, f32)> = None;
4451 for &(nid, rect, tstyle, _) in rects.iter() {
4452 let dy: f32 = if pos.get_y() < rect.get_y() {
4453 rect.get_y() - pos.get_y()
4454 } else if pos.get_y() > rect.bottom() {
4455 pos.get_y() - rect.bottom()
4456 } else {
4457 0.0
4458 };
4459 if dy > min_dy + 2.0 {
4460 continue;
4461 }
4462 let dx: f32 = if pos.get_x() < rect.get_x() {
4463 rect.get_x() - pos.get_x()
4464 } else if pos.get_x() > rect.right() {
4465 pos.get_x() - rect.right()
4466 } else {
4467 0.0
4468 };
4469 let better: bool = match best {
4470 None => true,
4471 Some((_, _, _, b_dx, b_dy)) => dx < b_dx || (dx == b_dx && dy < b_dy),
4472 };
4473 if better {
4474 best = Some((nid, rect, tstyle, dx, dy));
4475 }
4476 }
4477 let (best_nid, best_rect, best_style, _, _): (NodeId, Rect, TextStyle, f32, f32) = best?;
4478 let best_node: &SceneNode = self.get_node(best_nid)?;
4479 let NodeKind::Text(content) = best_node.get_kind() else {
4480 return None;
4481 };
4482 let min_y: f32 = best_rect.get_y() + 0.5;
4483 let max_y: f32 = (best_rect.bottom() - 0.5).max(min_y);
4484 let clamped_y: f32 = pos.get_y().clamp(min_y, max_y);
4485 let ch: usize = hit_test_text_char(
4486 content.as_str(),
4487 best_style,
4488 best_rect,
4489 Point::new(pos.get_x(), clamped_y),
4490 );
4491 Some((best_nid, ch))
4492 }
4493}
4494
4495impl SceneBorrowGuard {
4497 #[inline(always)]
4503 pub(crate) fn enter() -> Self {
4504 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4505 depth.set(depth.get().saturating_add(1));
4506 });
4507 Self
4508 }
4509}
4510
4511impl Drop for SceneBorrowGuard {
4513 #[inline(always)]
4519 fn drop(&mut self) {
4520 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4521 depth.set(depth.get().saturating_sub(1));
4522 });
4523 }
4524}
4525
4526impl SceneHandle {
4528 #[must_use]
4534 pub fn new_tree() -> Self {
4535 Self {
4536 inner: Rc::new(SceneHandleInner {
4537 tree: RefCell::new(SceneTree::default()),
4538 has_deferred: Cell::new(false),
4539 deferred_writes: RefCell::new(Vec::new()),
4540 }),
4541 }
4542 }
4543
4544 #[must_use]
4554 #[inline(always)]
4555 pub fn has_deferred_writes(&self) -> bool {
4556 let Self { inner } = self;
4557 inner.has_deferred.get()
4558 }
4559
4560 fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
4571 let mut executed: usize = 0;
4572 for _ in 0..MAX_FLUSH_ITERATIONS {
4573 let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
4574 Ok(mut queue) => {
4575 inner.has_deferred.set(false);
4576 if queue.is_empty() {
4577 break;
4578 }
4579 take(&mut *queue)
4580 }
4581 Err(_) => break,
4582 };
4583 for op in batch.into_iter() {
4584 op(tree);
4585 executed = executed.saturating_add(1);
4586 }
4587 if !inner.has_deferred.get() {
4588 break;
4589 }
4590 }
4591 executed
4592 }
4593
4594 pub fn flush_deferred_writes(&self) -> usize {
4604 let Self { inner } = self;
4605 if !inner.has_deferred.get() {
4606 return 0;
4607 }
4608 let executed: usize = match inner.tree.try_borrow_mut() {
4609 Ok(mut guard) => {
4610 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4611 Self::drain_deferred_locked(inner, &mut guard)
4612 }
4613 Err(_) => return 0,
4614 };
4615 if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
4616 self.flush_after_outer_borrow();
4617 }
4618 executed
4619 }
4620
4621 #[inline(always)]
4627 fn finish_outer_borrow(&self) {
4628 if is_scene_borrowed() || panicking() {
4629 return;
4630 }
4631 let Self { inner } = self;
4632 if !inner.has_deferred.get() && !has_deferred_effect_flush() {
4633 return;
4634 }
4635 self.flush_after_outer_borrow();
4636 }
4637
4638 #[cold]
4644 fn flush_after_outer_borrow(&self) {
4645 let Self { inner } = self;
4646 for _ in 0..MAX_FLUSH_ITERATIONS {
4647 let drained_writes: usize = if inner.has_deferred.get() {
4648 match inner.tree.try_borrow_mut() {
4649 Ok(mut guard) => {
4650 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4651 Self::drain_deferred_locked(inner, &mut guard)
4652 }
4653 Err(_) => 0,
4654 }
4655 } else {
4656 0
4657 };
4658 let flushed_effects: bool = if take_deferred_effect_flush() {
4659 flush_effects();
4660 true
4661 } else {
4662 false
4663 };
4664 if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
4665 break;
4666 }
4667 }
4668 }
4669
4670 pub fn mutate<CallbackFn>(&self, operation: CallbackFn)
4677 where
4678 CallbackFn: FnOnce(&mut SceneTree) + 'static,
4679 {
4680 let ran_inline: bool = {
4681 let Self { inner } = self;
4682 match inner.tree.try_borrow_mut() {
4683 Ok(mut guard) => {
4684 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4685 operation(&mut guard);
4686 if inner.has_deferred.get() {
4687 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4688 }
4689 true
4690 }
4691 Err(_) => {
4692 if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
4693 queue.push(Box::new(operation));
4694 inner.has_deferred.set(true);
4695 }
4696 notify_frame_needed();
4697 false
4698 }
4699 }
4700 };
4701 if ran_inline {
4702 self.finish_outer_borrow();
4703 }
4704 }
4705
4706 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
4715 self.mutate(move |tree: &mut SceneTree| {
4716 tree.set_virtual_scroll(id, scroll_y, content_height);
4717 });
4718 }
4719
4720 #[must_use]
4731 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
4732 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
4733 }
4734
4735 pub fn start_transition(&self, transition: NodeTransition) {
4742 self.mutate(move |tree: &mut SceneTree| {
4743 tree.start_transition(transition);
4744 });
4745 }
4746
4747 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
4755 self.mutate(move |tree: &mut SceneTree| {
4756 tree.mark_dirty(id, mask);
4757 });
4758 }
4759
4760 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
4768 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4769 |tree: &mut SceneTree| {
4770 if tree.get_node(parent).is_none() {
4771 return (Vec::new(), Vec::new());
4772 }
4773 let parent_idx: usize = parent.as_usize();
4774 let old_children: Vec<NodeId> = tree.children_vec(parent);
4775 tree.unlink_all_children_at(parent_idx);
4776 let mut all_scopes: Vec<Scope> = Vec::new();
4777 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
4778 if new_children.is_empty() {
4779 for old_child in old_children.into_iter() {
4780 let (scale_factor, ob): DisposedSubtreePayload =
4781 tree.dispose_subtree_collect(old_child);
4782 all_scopes.extend(scale_factor);
4783 all_obs.extend(ob);
4784 }
4785 } else if old_children.len() > 16 && new_children.len() > 16 {
4786 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
4787 for old_child in old_children.into_iter() {
4788 if !keep_set.contains(&old_child) {
4789 let (dpi_scale, ob): DisposedSubtreePayload =
4790 tree.dispose_subtree_collect(old_child);
4791 all_scopes.extend(dpi_scale);
4792 all_obs.extend(ob);
4793 }
4794 }
4795 } else {
4796 for old_child in old_children.into_iter() {
4797 if !new_children.contains(&old_child) {
4798 let (scroll_val, ob): DisposedSubtreePayload =
4799 tree.dispose_subtree_collect(old_child);
4800 all_scopes.extend(scroll_val);
4801 all_obs.extend(ob);
4802 }
4803 }
4804 }
4805 for child in new_children.into_iter() {
4806 if child == parent || tree.get_node(child).is_none() {
4807 continue;
4808 }
4809 let child_idx: usize = child.as_usize();
4810 let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
4811 if prev_parent != NODE_INDEX_NONE {
4812 tree.unlink_child_at(prev_parent as usize, child_idx);
4813 }
4814 tree.link_child_tail_at(parent_idx, parent, child_idx);
4815 }
4816 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4817 (all_scopes, all_obs)
4818 },
4819 (Vec::new(), Vec::new()),
4820 );
4821 finalize_disposed_subtree(scopes, observers);
4822 }
4823
4824 pub fn dismiss_portal_immediate(&self, portal: NodeId) {
4831 self.replace_children_safe(portal, Vec::new());
4832 self.with_write(
4833 |tree: &mut SceneTree| {
4834 tree.cancel_subtree_transitions(portal);
4835 tree.clear_subtree_hover(portal);
4836 if let Some(node) = tree.get_node_mut(portal) {
4837 let computed_style: &mut Style = node.get_mut_style();
4838 computed_style.get_mut_layout().set_display(Display::None);
4839 computed_style
4840 .get_mut_paint()
4841 .set_pointer_events(PointerEvents::None)
4842 .set_opacity(0.0);
4843 }
4844 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4845 tree.mark_dirty(portal, dirty_l | DIRTY_PAINT);
4846 tree.set_full_damage_pending(true);
4847 tree.clear_dirty_paint_queue();
4848 },
4849 (),
4850 );
4851 notify_frame_needed();
4852 }
4853
4854 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
4862 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4863 |tree: &mut SceneTree| {
4864 if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
4865 tree.unlink_child_at(parent.as_usize(), child.as_usize());
4866 }
4867 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
4868 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4869 out
4870 },
4871 (Vec::new(), Vec::new()),
4872 );
4873 finalize_disposed_subtree(scopes, observers);
4874 }
4875
4876 pub fn mutate_style<CallbackFn>(&self, id: NodeId, mutator: CallbackFn) -> bool
4888 where
4889 CallbackFn: FnOnce(&mut Style),
4890 {
4891 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
4892 }
4893
4894 pub fn freeze_subtree(&self, root: NodeId) {
4901 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4902 |tree: &mut SceneTree| {
4903 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4904 tree.cancel_subtree_transitions(root);
4905 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
4906 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4907 if layout.get_display() == Display::None {
4908 false
4909 } else {
4910 layout.set_display(Display::None);
4911 true
4912 }
4913 } else {
4914 false
4915 };
4916 if changed {
4917 tree.clear_subtree_hover(root);
4918 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4919 }
4920 obs
4921 },
4922 Vec::new(),
4923 );
4924 dispatch_lifecycle_freeze(&observers);
4925 }
4926
4927 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
4935 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4936 |tree: &mut SceneTree| {
4937 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4938 tree.cancel_subtree_transitions(root);
4939 let mut demoted_fixed: bool = false;
4940 let mut prev_z: i32 = 0;
4941 if let Some(node) = tree.get_node_mut(root) {
4942 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
4943 let computed_style: &mut Style = node.get_mut_style();
4944 prev_z = computed_style.layout_ref().get_z_index();
4945 demoted_fixed =
4946 !is_portal && computed_style.layout_ref().get_position() == Position::Fixed;
4947 computed_style
4948 .get_mut_layout()
4949 .set_position(Position::Absolute)
4950 .set_top(Some(0.0))
4951 .set_right(Some(0.0))
4952 .set_bottom(None)
4953 .set_left(Some(0.0))
4954 .set_z_index(0);
4955 computed_style
4956 .get_mut_paint()
4957 .set_pointer_events(PointerEvents::None);
4958 }
4959 if prev_z != 0 {
4960 let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
4961 if parent_idx != NODE_INDEX_NONE {
4962 tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
4963 }
4964 }
4965 tree.clear_subtree_hover(root);
4966 if demoted_fixed {
4967 tree.sync_portal_registration(root, false);
4968 }
4969 tree.start_transition(exit_transition.with_hide_on_complete(true));
4970 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4971 obs
4972 },
4973 Vec::new(),
4974 );
4975 dispatch_lifecycle_freeze(&observers);
4976 }
4977
4978 pub fn resume_subtree(&self, root: NodeId) {
4985 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4986 |tree: &mut SceneTree| {
4987 let mut unhidden: bool = false;
4988 if let Some(node) = tree.get_node_mut(root) {
4989 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4990 if layout.get_display() == Display::None {
4991 layout.set_display(Display::Flex);
4992 unhidden = true;
4993 }
4994 }
4995 if unhidden {
4996 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4997 } else {
4998 tree.mark_dirty(root, DIRTY_PAINT);
4999 }
5000 tree.collect_subtree_lifecycles(root)
5001 },
5002 Vec::new(),
5003 );
5004 dispatch_lifecycle_resume(&observers);
5005 }
5006
5007 pub fn activate_subtree(&self, root: NodeId) {
5014 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
5015 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
5016 Vec::new(),
5017 );
5018 dispatch_lifecycle_activate(&observers);
5019 }
5020
5021 pub fn update_subtree(&self, root: NodeId) {
5028 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
5029 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
5030 Vec::new(),
5031 );
5032 dispatch_lifecycle_update(&observers);
5033 }
5034
5035 pub fn emit_subtree_appear(&self, root: NodeId) {
5042 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
5043 |tree: &SceneTree| {
5044 (
5045 tree.collect_subtree_lifecycles(root),
5046 tree.collect_subtree_scope_ids(root),
5047 )
5048 },
5049 (Vec::new(), Vec::new()),
5050 );
5051 let system_event: SystemEvent = SystemEvent::Appear;
5052 dispatch_lifecycle_system_event(&observers, &system_event);
5053 dispatch_system_event_to_scopes(&scopes, &system_event);
5054 }
5055
5056 pub fn emit_subtree_disappear(&self, root: NodeId) {
5063 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
5064 |tree: &SceneTree| {
5065 (
5066 tree.collect_subtree_lifecycles(root),
5067 tree.collect_subtree_scope_ids(root),
5068 )
5069 },
5070 (Vec::new(), Vec::new()),
5071 );
5072 let system_event: SystemEvent = SystemEvent::Disappear;
5073 dispatch_lifecycle_system_event(&observers, &system_event);
5074 dispatch_system_event_to_scopes(&scopes, &system_event);
5075 }
5076
5077 #[must_use]
5087 pub fn has_active_transitions(&self) -> bool {
5088 self.with_read(SceneTree::has_active_transitions, false)
5089 }
5090
5091 #[must_use]
5101 pub fn get_selected_text(&self) -> Option<String> {
5102 self.with_read(SceneTree::get_selected_text, None)
5103 }
5104
5105 #[must_use]
5116 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
5117 self.with_read(
5118 |tree: &SceneTree| tree.get_selected_text_within(container),
5119 None,
5120 )
5121 }
5122
5123 pub fn clear_text_selection(&self) {
5129 self.mutate(SceneTree::clear_text_selection);
5130 }
5131
5132 pub fn with_read<CallbackFn, ReturnValue>(
5144 &self,
5145 operation: CallbackFn,
5146 fallback: ReturnValue,
5147 ) -> ReturnValue
5148 where
5149 CallbackFn: FnOnce(&SceneTree) -> ReturnValue,
5150 {
5151 let result: ReturnValue = {
5152 let Self { inner } = self;
5153 match inner.tree.try_borrow() {
5154 Ok(guard) => {
5155 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5156 operation(&guard)
5157 }
5158 Err(_) => return fallback,
5159 }
5160 };
5161 self.finish_outer_borrow();
5162 result
5163 }
5164
5165 pub fn with_write<CallbackFn, ReturnValue>(
5177 &self,
5178 operation: CallbackFn,
5179 fallback: ReturnValue,
5180 ) -> ReturnValue
5181 where
5182 CallbackFn: FnOnce(&mut SceneTree) -> ReturnValue,
5183 {
5184 let result: ReturnValue = {
5185 let Self { inner } = self;
5186 match inner.tree.try_borrow_mut() {
5187 Ok(mut guard) => {
5188 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5189 let out: ReturnValue = operation(&mut guard);
5190 if inner.has_deferred.get() {
5191 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
5192 }
5193 out
5194 }
5195 Err(_) => return fallback,
5196 }
5197 };
5198 self.finish_outer_borrow();
5199 result
5200 }
5201
5202 pub fn bind_text<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5214 where
5215 CallbackFn: FnMut() -> String + 'static,
5216 {
5217 let handle: Self = self.clone();
5218 Effect::new(move || {
5219 let value: String = producer();
5220 handle.mutate(move |tree: &mut SceneTree| {
5221 tree.set_text(node_id, value);
5222 });
5223 })
5224 }
5225
5226 pub fn bind_style<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5238 where
5239 CallbackFn: FnMut() -> Style + 'static,
5240 {
5241 let handle: Self = self.clone();
5242 Effect::new(move || {
5243 let style: Style = producer();
5244 handle.mutate(move |tree: &mut SceneTree| {
5245 tree.set_style(node_id, style);
5246 });
5247 })
5248 }
5249}
5250
5251impl Drop for ContextShared {
5253 fn drop(&mut self) {
5259 let Self {
5260 owned_signals,
5261 runtime_epoch,
5262 ..
5263 } = self;
5264 if *runtime_epoch != current_runtime_epoch() {
5265 return;
5266 }
5267 for sig_id in owned_signals.iter().copied() {
5268 let dropped: SignalSlot = with_runtime(
5269 |runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_signal(sig_id),
5270 SignalSlot::empty(),
5271 );
5272 drop(dropped);
5273 }
5274 }
5275}
5276
5277impl Context {
5279 #[must_use]
5290 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
5291 let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
5292 let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
5293 let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
5294 let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
5295 let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
5296 let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
5297 let system_back: Signal<u64> = Signal::new_detached(0);
5298 let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
5299 let live_fps: Signal<f32> = Signal::new_detached(60.0);
5300 let present_fps: Signal<f32> = Signal::new_detached(0.0);
5301 let is_idle: Signal<bool> = Signal::new_detached(true);
5302 let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
5303 let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
5304 let exit_requested: Signal<bool> = Signal::new_detached(false);
5305 let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
5306 let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
5307 let keyboard_visible: Signal<bool> = Signal::new_detached(false);
5308 let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
5309 let orientation: Signal<ScreenOrientation> =
5310 Signal::new_detached(ScreenOrientation::Landscape);
5311 let low_power_mode: Signal<bool> = Signal::new_detached(false);
5312 let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
5313 let window_focused: Signal<bool> = Signal::new_detached(true);
5314 let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
5315 let device_motion: Signal<DeviceMotionSample> =
5316 Signal::new_detached(DeviceMotionSample::default());
5317 let owned_signals: [SignalId; 24] = [
5318 breakpoint.id(),
5319 viewport_size.id(),
5320 theme_mode.id(),
5321 safe_area.id(),
5322 gesture.id(),
5323 swipe_drag_offset.id(),
5324 system_back.id(),
5325 fps_limit.id(),
5326 live_fps.id(),
5327 present_fps.id(),
5328 is_idle.id(),
5329 display_refresh_rate.id(),
5330 active_touches.id(),
5331 exit_requested.id(),
5332 app_state.id(),
5333 network_status.id(),
5334 keyboard_visible.id(),
5335 keyboard_height.id(),
5336 orientation.id(),
5337 low_power_mode.id(),
5338 locale.id(),
5339 window_focused.id(),
5340 immersive_fullscreen.id(),
5341 device_motion.id(),
5342 ];
5343 Self {
5344 scene,
5345 breakpoint,
5346 viewport_size,
5347 theme_mode,
5348 platform,
5349 safe_area,
5350 gesture,
5351 swipe_drag_offset,
5352 system_back,
5353 dynamic_hub: DynamicUpdateHub::new(),
5354 fps_limit,
5355 live_fps,
5356 present_fps,
5357 is_idle,
5358 display_refresh_rate,
5359 active_touches,
5360 exit_requested,
5361 app_state,
5362 network_status,
5363 keyboard_visible,
5364 keyboard_height,
5365 orientation,
5366 low_power_mode,
5367 locale,
5368 window_focused,
5369 immersive_fullscreen,
5370 device_motion,
5371 shared: Rc::new(ContextShared {
5372 fullscreen_depth: Cell::new(0),
5373 clock_ms: Cell::new(0),
5374 owned_signals,
5375 runtime_epoch: current_runtime_epoch(),
5376 }),
5377 }
5378 }
5379
5380 #[must_use]
5390 pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
5391 self.get_safe_area()
5392 }
5393
5394 #[must_use]
5404 pub fn safe_area(&self) -> SafeAreaInsets {
5405 self.get_safe_area().get()
5406 }
5407
5408 #[must_use]
5418 pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
5419 self.get_immersive_fullscreen()
5420 }
5421
5422 #[must_use]
5432 pub fn is_immersive_fullscreen(&self) -> bool {
5433 self.get_immersive_fullscreen().get()
5434 }
5435
5436 pub fn set_immersive_fullscreen(&self, enabled: bool) {
5443 let Self { shared, .. } = self;
5444 let changed: bool = if enabled {
5445 if shared.fullscreen_depth.get() == 0 {
5446 shared.fullscreen_depth.set(1);
5447 }
5448 self.get_immersive_fullscreen().set_if_changed(true)
5449 } else {
5450 shared.fullscreen_depth.set(0);
5451 self.get_immersive_fullscreen().set_if_changed(false)
5452 };
5453 if changed {
5454 notify_frame_needed();
5455 }
5456 }
5457
5458 pub fn enter_immersive_fullscreen(&self) {
5464 let Self { shared, .. } = self;
5465 let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
5466 shared.fullscreen_depth.set(next);
5467 if self.get_immersive_fullscreen().set_if_changed(true) {
5468 notify_frame_needed();
5469 }
5470 }
5471
5472 pub fn exit_immersive_fullscreen(&self) {
5478 let Self { shared, .. } = self;
5479 let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
5480 shared.fullscreen_depth.set(next);
5481 if next == 0 && self.get_immersive_fullscreen().set_if_changed(false) {
5482 notify_frame_needed();
5483 }
5484 }
5485
5486 #[must_use]
5496 pub fn app_state_signal(&self) -> Signal<AppState> {
5497 self.get_app_state()
5498 }
5499
5500 pub fn emit_page_appear(&self) {
5506 let system_event: SystemEvent = SystemEvent::Appear;
5507 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5508 .get_scene()
5509 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5510 dispatch_lifecycle_system_event(&observers, &system_event);
5511 dispatch_system_event_listeners(&system_event);
5512 }
5513
5514 pub fn emit_page_disappear(&self) {
5520 let system_event: SystemEvent = SystemEvent::Disappear;
5521 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5522 .get_scene()
5523 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5524 dispatch_lifecycle_system_event(&observers, &system_event);
5525 dispatch_system_event_listeners(&system_event);
5526 }
5527
5528 pub fn emit_subtree_appear(&self, root: NodeId) {
5535 self.get_scene().emit_subtree_appear(root);
5536 }
5537
5538 pub fn emit_subtree_disappear(&self, root: NodeId) {
5545 self.get_scene().emit_subtree_disappear(root);
5546 }
5547
5548 #[must_use]
5558 pub fn elapsed_ms(&self) -> u64 {
5559 let Self { shared, .. } = self;
5560 shared.clock_ms.get()
5561 }
5562
5563 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
5570 let Self { shared, .. } = self;
5571 shared
5572 .clock_ms
5573 .set(shared.clock_ms.get().saturating_add(delta_ms));
5574 }
5575
5576 pub fn request_exit(&self) {
5582 let _: bool = self.get_exit_requested().set_if_changed(true);
5583 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
5584 }
5585
5586 pub fn copy_to_clipboard(&self, text: &str) -> bool {
5597 write_system_clipboard(text)
5598 }
5599
5600 pub fn view(&mut self, style: Style) -> NodeId {
5611 self.get_scene().with_write(
5612 |tree: &mut SceneTree| tree.create_view(style),
5613 NodeId::default(),
5614 )
5615 }
5616
5617 pub fn text(&mut self, content: String, style: Style) -> NodeId {
5629 self.get_scene().with_write(
5630 |tree: &mut SceneTree| tree.create_text(content, style),
5631 NodeId::default(),
5632 )
5633 }
5634
5635 pub fn reactive_text<CallbackFn>(&mut self, style: Style, producer: CallbackFn) -> NodeId
5647 where
5648 CallbackFn: FnMut() -> String + 'static,
5649 {
5650 let node_id: NodeId = self.text(String::new(), style);
5651 let handle: SceneHandle = self.get_scene().clone();
5652 let (scope, _): (Scope, Effect) =
5653 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
5654 self.get_scene().with_write(
5655 |tree: &mut SceneTree| {
5656 tree.attach_scope(node_id, scope);
5657 },
5658 (),
5659 );
5660 node_id
5661 }
5662
5663 pub fn scroll_view(&mut self, style: Style) -> NodeId {
5674 self.get_scene().with_write(
5675 |tree: &mut SceneTree| tree.create_scroll_view(style),
5676 NodeId::default(),
5677 )
5678 }
5679
5680 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
5692 self.get_scene().with_write(
5693 |tree: &mut SceneTree| tree.create_input(state, style),
5694 NodeId::default(),
5695 )
5696 }
5697
5698 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
5710 self.get_scene().with_write(
5711 |tree: &mut SceneTree| tree.create_image(buffer, style),
5712 NodeId::default(),
5713 )
5714 }
5715
5716 pub fn canvas<CallbackFn>(&mut self, style: Style, painter: CallbackFn) -> NodeId
5728 where
5729 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5730 {
5731 self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
5732 }
5733
5734 pub fn canvas_with_caching<CallbackFn>(
5747 &mut self,
5748 style: Style,
5749 caching: CanvasCaching,
5750 painter: CallbackFn,
5751 ) -> NodeId
5752 where
5753 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5754 {
5755 let callback_fn: CanvasDrawCallback = Rc::new(RefCell::new(painter));
5756 self.get_scene().with_write(
5757 |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, callback_fn),
5758 NodeId::default(),
5759 )
5760 }
5761
5762 pub fn portal(&mut self, style: Style) -> NodeId {
5773 self.get_scene().with_write(
5774 |tree: &mut SceneTree| tree.create_portal(style),
5775 NodeId::default(),
5776 )
5777 }
5778
5779 pub fn fragment(&mut self) -> NodeId {
5789 self.get_scene().with_write(
5790 |tree: &mut SceneTree| tree.create_fragment(),
5791 NodeId::default(),
5792 )
5793 }
5794
5795 pub fn append(&mut self, parent: NodeId, child: NodeId) {
5803 self.get_scene().with_write(
5804 |tree: &mut SceneTree| {
5805 tree.append_child(parent, child);
5806 },
5807 (),
5808 );
5809 }
5810
5811 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
5819 if children.is_empty() {
5820 return;
5821 }
5822 self.get_scene().with_write(
5823 |tree: &mut SceneTree| {
5824 tree.append_children(parent, children);
5825 },
5826 (),
5827 );
5828 }
5829
5830 pub fn bind_style<CallbackFn>(&mut self, node_id: NodeId, producer: CallbackFn)
5838 where
5839 CallbackFn: FnMut() -> Style + 'static,
5840 {
5841 let handle: SceneHandle = self.get_scene().clone();
5842 let (scope, _): (Scope, Effect) =
5843 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
5844 self.get_scene().with_write(
5845 |tree: &mut SceneTree| {
5846 tree.attach_scope(node_id, scope);
5847 },
5848 (),
5849 );
5850 }
5851
5852 pub fn on_pointer_enter<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5860 where
5861 CallbackFn: FnMut(&UiEvent) + 'static,
5862 {
5863 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5864 self.get_scene().with_write(
5865 |tree: &mut SceneTree| {
5866 if let Some(node) = tree.get_node_mut(node_id) {
5867 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5868 }
5869 },
5870 (),
5871 );
5872 }
5873
5874 pub fn on_pointer_leave<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_pointer_leave(Some(handler));
5890 }
5891 },
5892 (),
5893 );
5894 }
5895
5896 pub fn on_focus<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5904 where
5905 CallbackFn: FnMut(&UiEvent) + 'static,
5906 {
5907 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5908 self.get_scene().with_write(
5909 |tree: &mut SceneTree| {
5910 if let Some(node) = tree.get_node_mut(node_id) {
5911 node.get_mut_handlers().set_on_focus(Some(handler));
5912 node.get_mut_interaction().set_focusable(true);
5913 }
5914 },
5915 (),
5916 );
5917 }
5918
5919 pub fn on_blur<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5927 where
5928 CallbackFn: FnMut(&UiEvent) + 'static,
5929 {
5930 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5931 self.get_scene().with_write(
5932 |tree: &mut SceneTree| {
5933 if let Some(node) = tree.get_node_mut(node_id) {
5934 node.get_mut_handlers().set_on_blur(Some(handler));
5935 }
5936 },
5937 (),
5938 );
5939 }
5940
5941 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
5949 self.get_scene().with_write(
5950 |tree: &mut SceneTree| {
5951 if let Some(node) = tree.get_node_mut(node_id) {
5952 node.get_mut_interaction().set_focusable(focusable);
5953 }
5954 },
5955 (),
5956 );
5957 }
5958
5959 pub fn on_click<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5967 where
5968 CallbackFn: FnMut(&UiEvent) + 'static,
5969 {
5970 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5971 self.get_scene().with_write(
5972 |tree: &mut SceneTree| {
5973 if let Some(node) = tree.get_node_mut(node_id) {
5974 node.get_mut_handlers().set_on_click(Some(handler));
5975 node.get_mut_interaction().set_focusable(true);
5976 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5977 if paint.get_cursor() == CursorIcon::Default {
5978 paint.set_cursor(CursorIcon::Pointer);
5979 }
5980 }
5981 },
5982 (),
5983 );
5984 }
5985
5986 pub fn on_change<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5994 where
5995 CallbackFn: FnMut(&UiEvent) + 'static,
5996 {
5997 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5998 self.get_scene().with_write(
5999 |tree: &mut SceneTree| {
6000 if let Some(node) = tree.get_node_mut(node_id) {
6001 node.get_mut_handlers().set_on_change(Some(handler));
6002 }
6003 },
6004 (),
6005 );
6006 }
6007
6008 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
6016 self.get_scene().with_write(
6017 |tree: &mut SceneTree| {
6018 if let Some(node) = tree.get_node_mut(node_id) {
6019 node.set_a11y(Some(props));
6020 }
6021 },
6022 (),
6023 );
6024 }
6025
6026 pub fn on_scroll<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6034 where
6035 CallbackFn: FnMut(&UiEvent) + 'static,
6036 {
6037 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6038 self.get_scene().with_write(
6039 |tree: &mut SceneTree| {
6040 if let Some(node) = tree.get_node_mut(node_id) {
6041 node.get_mut_handlers().set_on_scroll(Some(handler));
6042 }
6043 },
6044 (),
6045 );
6046 }
6047
6048 pub fn on_pointer_down<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6056 where
6057 CallbackFn: FnMut(&UiEvent) + 'static,
6058 {
6059 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6060 self.get_scene().with_write(
6061 |tree: &mut SceneTree| {
6062 if let Some(node) = tree.get_node_mut(node_id) {
6063 node.get_mut_handlers().set_on_pointer_down(Some(handler));
6064 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
6065 if paint.get_cursor() == CursorIcon::Default {
6066 paint.set_cursor(CursorIcon::Pointer);
6067 }
6068 }
6069 },
6070 (),
6071 );
6072 }
6073
6074 pub fn on_pointer_move<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6082 where
6083 CallbackFn: FnMut(&UiEvent) + 'static,
6084 {
6085 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6086 self.get_scene().with_write(
6087 |tree: &mut SceneTree| {
6088 if let Some(node) = tree.get_node_mut(node_id) {
6089 node.get_mut_handlers().set_on_pointer_move(Some(handler));
6090 }
6091 },
6092 (),
6093 );
6094 }
6095
6096 pub fn on_pointer_up<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6104 where
6105 CallbackFn: FnMut(&UiEvent) + 'static,
6106 {
6107 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
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_up(Some(handler));
6112 }
6113 },
6114 (),
6115 );
6116 }
6117
6118 pub fn on_pointer_cancel<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6126 where
6127 CallbackFn: FnMut(&UiEvent) + 'static,
6128 {
6129 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6130 self.get_scene().with_write(
6131 |tree: &mut SceneTree| {
6132 if let Some(node) = tree.get_node_mut(node_id) {
6133 node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
6134 }
6135 },
6136 (),
6137 );
6138 }
6139
6140 pub fn on_hover<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6148 where
6149 CallbackFn: FnMut(&UiEvent) + 'static,
6150 {
6151 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6152 let leave_handler: UiEventHandler = handler.clone();
6153 self.get_scene().with_write(
6154 |tree: &mut SceneTree| {
6155 if let Some(node) = tree.get_node_mut(node_id) {
6156 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
6157 node.get_mut_handlers()
6158 .set_on_pointer_leave(Some(leave_handler));
6159 }
6160 },
6161 (),
6162 );
6163 }
6164
6165 pub fn on_key<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6173 where
6174 CallbackFn: FnMut(&UiEvent) + 'static,
6175 {
6176 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6177 self.get_scene().with_write(
6178 |tree: &mut SceneTree| {
6179 if let Some(node) = tree.get_node_mut(node_id) {
6180 node.get_mut_handlers().set_on_key_down(Some(handler));
6181 node.get_mut_interaction().set_focusable(true);
6182 }
6183 },
6184 (),
6185 );
6186 }
6187
6188 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
6197 self.get_scene()
6198 .set_virtual_scroll(node_id, scroll_y, content_height);
6199 }
6200
6201 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
6209 self.get_scene().with_write(
6210 |tree: &mut SceneTree| {
6211 tree.set_scroll_offset(node_id, offset);
6212 },
6213 (),
6214 );
6215 }
6216
6217 pub fn start_transition(&mut self, transition: NodeTransition) {
6224 self.get_scene().start_transition(transition);
6225 }
6226
6227 pub fn bind_children<CallbackFn>(&mut self, host: NodeId, mut builder: CallbackFn)
6235 where
6236 CallbackFn: FnMut() -> Vec<NodeId> + 'static,
6237 {
6238 let ctx_clone: Self = self.clone();
6239 let handle: SceneHandle = self.get_scene().clone();
6240 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6241 Effect::new(move || {
6242 let (child_scope, children): (Scope, Vec<NodeId>) =
6243 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
6244 let first_opt: Option<NodeId> = children.first().copied();
6245 handle.replace_children_safe(host, children);
6246 if let Some(first) = first_opt {
6247 handle.mutate(move |tree: &mut SceneTree| {
6248 tree.attach_scope(first, child_scope);
6249 });
6250 } else {
6251 child_scope.dispose();
6252 }
6253 })
6254 });
6255 self.get_scene().mutate(move |tree: &mut SceneTree| {
6256 tree.attach_scope(host, scope);
6257 });
6258 }
6259
6260 pub fn bind_children_keyed<ValueType, KeyType, Items, KeyFn, RenderFn>(
6270 &mut self,
6271 host: NodeId,
6272 mut items_fn: Items,
6273 mut key_fn: KeyFn,
6274 mut render_fn: RenderFn,
6275 ) where
6276 ValueType: 'static,
6277 KeyType: Eq + Hash + 'static,
6278 Items: FnMut() -> Vec<ValueType> + 'static,
6279 KeyFn: FnMut(&ValueType) -> KeyType + 'static,
6280 RenderFn: FnMut(ValueType) -> NodeId + 'static,
6281 {
6282 let ctx_clone: Self = self.clone();
6283 let handle: SceneHandle = self.get_scene().clone();
6284 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6285 let mut live_nodes: HashMap<KeyType, NodeId> = HashMap::new();
6286 Effect::new(move || {
6287 let next_items: Vec<ValueType> = items_fn();
6288 let mut next_map: HashMap<KeyType, NodeId> =
6289 HashMap::with_capacity(next_items.len());
6290 let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
6291 let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
6292 for item in next_items.into_iter() {
6293 let key: KeyType = key_fn(&item);
6294 if let Some(existing_id) = live_nodes.remove(&key) {
6295 next_children.push(existing_id);
6296 let _: Option<NodeId> = next_map.insert(key, existing_id);
6297 } else {
6298 let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
6299 with_context(ctx_clone.clone(), || render_fn(item))
6300 });
6301 new_scopes.push((mounted_id, item_scope));
6302 next_children.push(mounted_id);
6303 let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
6304 }
6305 }
6306 live_nodes = next_map;
6307 handle.replace_children_safe(host, next_children);
6308 if !new_scopes.is_empty() {
6309 handle.mutate(move |tree: &mut SceneTree| {
6310 for (nid, item_scope) in new_scopes.into_iter() {
6311 tree.attach_scope(nid, item_scope);
6312 }
6313 });
6314 }
6315 })
6316 });
6317 self.get_scene().mutate(move |tree: &mut SceneTree| {
6318 tree.attach_scope(host, scope);
6319 });
6320 }
6321}
6322
6323impl Drop for ContextGuard {
6325 fn drop(&mut self) {
6331 let Self { previous } = self;
6332 let restored: Option<Context> = previous.take();
6333 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
6334 *slot.borrow_mut() = restored;
6335 });
6336 }
6337}
6338
6339impl NodeRefTarget for NodeId {
6341 fn bind_node_ref(&mut self, id: NodeId) {
6348 *self = id;
6349 }
6350}
6351
6352impl NodeRefTarget for Option<NodeId> {
6354 fn bind_node_ref(&mut self, id: NodeId) {
6361 *self = Some(id);
6362 }
6363}
6364
6365impl NodeRefTarget for Cell<NodeId> {
6367 fn bind_node_ref(&mut self, id: NodeId) {
6374 self.set(id);
6375 }
6376}
6377
6378impl NodeRefTarget for Rc<Cell<NodeId>> {
6380 fn bind_node_ref(&mut self, id: NodeId) {
6387 self.set(id);
6388 }
6389}
6390
6391impl NodeRefTarget for Cell<Option<NodeId>> {
6393 fn bind_node_ref(&mut self, id: NodeId) {
6400 self.set(Some(id));
6401 }
6402}
6403
6404impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
6406 fn bind_node_ref(&mut self, id: NodeId) {
6413 self.set(Some(id));
6414 }
6415}
6416
6417impl TextNodeContent for String {
6419 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6431 ctx.text(self, style)
6432 }
6433
6434 fn mount_text_current(self, style: Style) -> NodeId {
6445 with_current_context(|ctx: &Context| {
6446 ctx.get_scene().with_write(
6447 |tree: &mut SceneTree| tree.create_text(self, style),
6448 NodeId::default(),
6449 )
6450 })
6451 }
6452}
6453
6454impl TextNodeContent for &str {
6456 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6468 ctx.text(self.to_string(), style)
6469 }
6470
6471 fn mount_text_current(self, style: Style) -> NodeId {
6482 let owned: String = self.to_string();
6483 with_current_context(|ctx: &Context| {
6484 ctx.get_scene().with_write(
6485 |tree: &mut SceneTree| tree.create_text(owned, style),
6486 NodeId::default(),
6487 )
6488 })
6489 }
6490}
6491
6492impl TextNodeContent for &String {
6494 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6506 ctx.text(self.clone(), style)
6507 }
6508
6509 fn mount_text_current(self, style: Style) -> NodeId {
6520 let owned: String = self.clone();
6521 with_current_context(|ctx: &Context| {
6522 ctx.get_scene().with_write(
6523 |tree: &mut SceneTree| tree.create_text(owned, style),
6524 NodeId::default(),
6525 )
6526 })
6527 }
6528}
6529
6530impl TextNodeContent for Cow<'_, str> {
6532 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6544 ctx.text(self.into_owned(), style)
6545 }
6546
6547 fn mount_text_current(self, style: Style) -> NodeId {
6558 let owned: String = self.into_owned();
6559 with_current_context(|ctx: &Context| {
6560 ctx.get_scene().with_write(
6561 |tree: &mut SceneTree| tree.create_text(owned, style),
6562 NodeId::default(),
6563 )
6564 })
6565 }
6566}
6567
6568impl<CallbackFn, TextValue> TextNodeContent for CallbackFn
6570where
6571 CallbackFn: FnMut() -> TextValue + 'static,
6572 TextValue: Into<String>,
6573{
6574 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
6586 ctx.reactive_text(style, move || self().into())
6587 }
6588
6589 fn mount_text_current(mut self, style: Style) -> NodeId {
6600 mount_reactive_text(style, move || self().into())
6601 }
6602}