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 scrollbars_suppressed: false,
148 }
149 }
150}
151
152impl SceneTree {
154 fn live_generation(&self, id: NodeId) -> Option<u32> {
165 let meta: &NodeMeta = self.get_meta().get(id.as_usize())?;
166 ((meta.get_flags() & NODE_FLAG_ALIVE) != 0 && meta.get_generation() == id.get_generation())
167 .then_some(id.get_generation())
168 }
169
170 fn theme_entry(&self, id: NodeId) -> Option<ThemeNodeEntry> {
181 let generation: u32 = self.live_generation(id)?;
182 let Self { theme_entries, .. } = self;
183 theme_entries
184 .get(&id.get_index())
185 .copied()
186 .filter(|entry: &ThemeNodeEntry| entry.get_generation() == generation)
187 }
188
189 fn update_theme_entry<CallbackFn>(&mut self, id: NodeId, apply: CallbackFn)
197 where
198 CallbackFn: FnOnce(&mut ThemeNodeEntry),
199 {
200 let Some(generation) = self.live_generation(id) else {
201 return;
202 };
203 let Self { theme_entries, .. } = self;
204 let entry: &mut ThemeNodeEntry = theme_entries
205 .entry(id.get_index())
206 .or_insert_with(|| ThemeNodeEntry::new(generation, false, None));
207 if entry.get_generation() != generation {
208 *entry = ThemeNodeEntry::new(generation, false, None);
209 }
210 apply(entry);
211 }
212
213 pub fn set_theme_owned(&mut self, id: NodeId, owned: bool) {
221 if !owned && self.theme_entry(id).is_none() {
222 return;
223 }
224 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
225 entry.set_owned(owned);
226 });
227 }
228
229 #[must_use]
240 pub fn is_theme_owned(&self, id: NodeId) -> bool {
241 self.theme_entry(id)
242 .is_some_and(|entry: ThemeNodeEntry| entry.get_owned())
243 }
244
245 #[must_use]
256 pub fn theme_baseline(&self, id: NodeId) -> Option<ThemeBaseline> {
257 self.theme_entry(id)
258 .and_then(|entry: ThemeNodeEntry| entry.get_baseline())
259 }
260
261 pub fn set_theme_baseline(&mut self, id: NodeId, baseline: Option<ThemeBaseline>) {
269 if baseline.is_none() && self.theme_entry(id).is_none() {
270 return;
271 }
272 self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
273 entry.set_baseline(baseline);
274 });
275 }
276}
277
278impl SceneTree {
280 pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
288 if self.get_node(id).is_none() {
289 return;
290 }
291 let clamped: f32 = if blur_radius.is_finite() {
292 blur_radius.clamp(0.0, 96.0)
293 } else {
294 0.0
295 };
296 let prev_radius: f32 = self.backdrop_blur_radius(id);
297 if (prev_radius - clamped).abs() <= 0.001 {
298 return;
299 }
300 if prev_radius > 0.0 {
301 self.record_node_logical_damage(id);
302 }
303 let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
304 if clamped <= 0.0 {
305 blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
306 } else if let Some(slot) = blurs
307 .iter_mut()
308 .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
309 {
310 slot.1 = clamped;
311 } else {
312 blurs.push((id, clamped));
313 }
314 let paint_copy: Option<PaintStyle> =
315 self.get_node(id).map(|node: &SceneNode| *node.paint_ref());
316 if let Some(paint) = paint_copy {
317 self.sync_node_compact_paint(id.as_usize(), &paint, clamped);
318 }
319 self.mark_dirty(id, DIRTY_PAINT);
320 }
321
322 #[must_use]
333 pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
334 for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
335 if nid == id {
336 return radius;
337 }
338 }
339 0.0
340 }
341
342 #[must_use]
352 pub fn has_backdrop_blur_nodes(&self) -> bool {
353 !self.get_backdrop_blur_nodes().is_empty()
354 }
355
356 pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
368 if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
369 return 0;
370 }
371 let clamped_scale: f32 = scale.max(0.5);
372 let blur_count: usize = self.get_backdrop_blur_nodes().len();
373 let mut dirtied: Vec<bool> = vec![false; blur_count];
374 let mut total_added: usize = 0;
375 let mut changed: bool = true;
376 while changed && !damage.get_full_damage() {
377 changed = false;
378 if damage.bounds_rect().is_none() {
379 break;
380 }
381 for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
382 if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
383 continue;
384 }
385 let Some(screen_rect) = self.node_screen_bounds(nid) else {
386 continue;
387 };
388 if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
389 continue;
390 }
391 let sigma: f32 = (blur_radius * 0.5).max(0.75);
392 let halo: f32 = (sigma * 3.0).ceil() + 2.0;
393 let sample_logical: Rect = Rect::new(
394 screen_rect.get_x() - halo,
395 screen_rect.get_y() - halo,
396 screen_rect.get_width() + halo * 2.0,
397 screen_rect.get_height() + halo * 2.0,
398 );
399 let sample_phys: Rect =
400 Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
401 let output_phys: Rect = Self::scale_logical_to_phys_rect(
402 Rect::new(
403 screen_rect.get_x() - 2.0,
404 screen_rect.get_y() - 2.0,
405 screen_rect.get_width() + 4.0,
406 screen_rect.get_height() + 4.0,
407 ),
408 clamped_scale,
409 );
410 let (rects, count): ([Rect; 8], usize) =
411 damage.normalized_rects(u32::MAX, u32::MAX);
412 let overlaps: bool = rects
413 .iter()
414 .take(count)
415 .any(|rect_bounds: &Rect| rect_bounds.intersect(sample_phys).is_some());
416 if overlaps {
417 damage.add_rect(output_phys);
418 dirtied[idx] = true;
419 total_added += 1;
420 changed = true;
421 }
422 }
423 }
424 total_added
425 }
426
427 pub fn effect_dependency_damage(
443 &self,
444 dirty_set: &mut DirtyRectSet,
445 extra_portals: &[PortalBackdropRegion],
446 viewport_w: u32,
447 viewport_h: u32,
448 scale: f32,
449 full_ratio_threshold: f32,
450 ) -> EffectDamageReport {
451 if dirty_set.get_full_frame() {
452 return EffectDamageReport::new(
453 0,
454 extra_portals.len() + self.get_backdrop_blur_nodes().len(),
455 true,
456 );
457 }
458 let mut combined: Vec<PortalBackdropRegion> =
459 Vec::with_capacity(extra_portals.len() + self.get_backdrop_blur_nodes().len());
460 combined.extend_from_slice(extra_portals);
461 for &(nid, blur_radius) in self.get_backdrop_blur_nodes().iter() {
462 if blur_radius <= 0.0 || !self.is_node_visible(nid) {
463 continue;
464 }
465 if let Some(screen_rect) = self.node_screen_bounds(nid)
466 && screen_rect.get_width() > 0.0
467 && screen_rect.get_height() > 0.0
468 {
469 let is_dirty: bool = self
470 .get_node(nid)
471 .map(|scene_node: &SceneNode| scene_node.get_dirty().get_bits() != DIRTY_NONE)
472 .unwrap_or(false);
473 combined.push(PortalBackdropRegion::new(
474 screen_rect,
475 blur_radius,
476 is_dirty,
477 ));
478 }
479 }
480 dirty_set.apply_effect_dependency_damage(
481 &combined,
482 viewport_w,
483 viewport_h,
484 scale,
485 full_ratio_threshold,
486 )
487 }
488
489 #[must_use]
499 #[inline(always)]
500 pub fn portal_nodes(&self) -> &[NodeId] {
501 let Self { portal_nodes, .. } = self;
502 portal_nodes.as_slice()
503 }
504
505 #[must_use]
515 #[inline(always)]
516 pub fn has_portal_nodes(&self) -> bool {
517 let Self { portal_nodes, .. } = self;
518 !portal_nodes.is_empty()
519 }
520
521 fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
529 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
530 let next: u16 = if is_portal {
531 meta.get_flags() | NODE_FLAG_IS_PORTAL
532 } else {
533 meta.get_flags() & !NODE_FLAG_IS_PORTAL
534 };
535 let _: &mut NodeMeta = meta.set_flags(next);
536 }
537 let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
538 if is_portal {
539 if !portals.contains(&id) {
540 portals.push(id);
541 }
542 } else if !portals.is_empty() {
543 portals.retain(|existing: &NodeId| *existing != id);
544 }
545 }
546
547 #[must_use]
557 #[inline(always)]
558 pub fn scroll_nodes(&self) -> &[NodeId] {
559 let Self { scroll_nodes, .. } = self;
560 scroll_nodes.as_slice()
561 }
562
563 #[must_use]
573 #[inline(always)]
574 pub fn has_scroll_nodes(&self) -> bool {
575 let Self { scroll_nodes, .. } = self;
576 !scroll_nodes.is_empty()
577 }
578
579 fn sync_scroll_registration(&mut self, id: NodeId, is_scroll: bool) {
587 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
588 let next: u16 = if is_scroll {
589 meta.get_flags() | NODE_FLAG_IS_SCROLL_CONTAINER
590 } else {
591 meta.get_flags() & !NODE_FLAG_IS_SCROLL_CONTAINER
592 };
593 let _: &mut NodeMeta = meta.set_flags(next);
594 }
595 let scrolls: &mut Vec<NodeId> = self.get_mut_scroll_nodes();
596 if is_scroll {
597 if !scrolls.contains(&id) {
598 scrolls.push(id);
599 }
600 } else if !scrolls.is_empty() {
601 scrolls.retain(|existing: &NodeId| *existing != id);
602 }
603 }
604
605 fn sync_node_compact_paint(&mut self, idx: usize, paint: &PaintStyle, blur: f32) {
614 let prev_effect_id: u32 = self
615 .get_compact_paints()
616 .get(idx)
617 .map(CompactPaintStyle::get_effect_id)
618 .unwrap_or(EFFECT_ID_NONE);
619 let entry: PaintEffectEntry = PaintEffectEntry::from_paint_and_blur(paint, blur);
620 let next_effect_id: u32 = self.get_mut_effect_table().update(prev_effect_id, entry);
621 let compact: CompactPaintStyle = CompactPaintStyle::from_paint(paint, next_effect_id);
622 if let Some(slot) = self.get_mut_compact_paints().get_mut(idx) {
623 *slot = compact;
624 }
625 }
626
627 #[must_use]
638 #[inline(always)]
639 pub fn compact_paint(&self, id: NodeId) -> Option<&CompactPaintStyle> {
640 let idx: usize = id.as_usize();
641 let meta: &NodeMeta = self.get_meta().get(idx)?;
642 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
643 {
644 return None;
645 }
646 self.get_compact_paints().get(idx)
647 }
648
649 #[must_use]
660 #[inline(always)]
661 pub fn paint_effect(&self, id: NodeId) -> Option<&PaintEffectEntry> {
662 let effect_id: u32 = self.compact_paint(id)?.get_effect_id();
663 self.get_effect_table().get(effect_id)
664 }
665
666 #[must_use]
676 #[inline(always)]
677 pub fn effect_table(&self) -> &EffectTable {
678 self.get_effect_table()
679 }
680
681 #[must_use]
692 #[inline(always)]
693 pub fn has_extras(&self, id: NodeId) -> bool {
694 let Some(node) = self.get_node(id) else {
695 return false;
696 };
697 node.has_extras()
698 }
699
700 #[must_use]
711 #[inline(always)]
712 pub fn has_nonzero_z_child(&self, id: NodeId) -> bool {
713 let idx: usize = id.as_usize();
714 let Some(meta) = self.get_meta().get(idx) else {
715 return false;
716 };
717 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
718 && meta.get_generation() == id.get_generation()
719 && (meta.get_flags() & NODE_FLAG_HAS_NONZERO_Z_CHILD) != 0
720 }
721
722 #[must_use]
733 #[inline(always)]
734 pub fn has_lifecycle(&self, id: NodeId) -> bool {
735 let idx: usize = id.as_usize();
736 let Some(meta) = self.get_meta().get(idx) else {
737 return false;
738 };
739 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
740 && meta.get_generation() == id.get_generation()
741 && (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
742 }
743
744 #[must_use]
755 #[inline(always)]
756 pub fn has_scope(&self, id: NodeId) -> bool {
757 let idx: usize = id.as_usize();
758 let Some(meta) = self.get_meta().get(idx) else {
759 return false;
760 };
761 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
762 && meta.get_generation() == id.get_generation()
763 && (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
764 }
765
766 #[must_use]
777 #[inline(always)]
778 pub fn children_iter(&self, parent: NodeId) -> SceneChildIter<'_> {
779 let idx: usize = parent.as_usize();
780 let valid: bool = self.get_meta().get(idx).is_some_and(|meta: &NodeMeta| {
781 (meta.get_flags() & NODE_FLAG_ALIVE) != 0
782 && meta.get_generation() == parent.get_generation()
783 });
784 if !valid {
785 return SceneChildIter {
786 meta: self.get_meta().as_slice(),
787 topology: self.get_topology().as_slice(),
788 head: NODE_INDEX_NONE,
789 tail: NODE_INDEX_NONE,
790 remaining: 0,
791 };
792 }
793 let topo: NodeTopology = self.get_topology()[idx];
794 SceneChildIter {
795 meta: self.get_meta().as_slice(),
796 topology: self.get_topology().as_slice(),
797 head: topo.get_first_child(),
798 tail: topo.get_last_child(),
799 remaining: topo.get_child_count() as usize,
800 }
801 }
802
803 #[inline]
811 pub fn for_each_child<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
812 where
813 CallbackFn: FnMut(NodeId),
814 {
815 for child_id in self.children_iter(parent) {
816 visit(child_id);
817 }
818 }
819
820 #[inline]
828 pub fn for_each_child_rev<CallbackFn>(&self, parent: NodeId, mut visit: CallbackFn)
829 where
830 CallbackFn: FnMut(NodeId),
831 {
832 for child_id in self.children_iter(parent).rev() {
833 visit(child_id);
834 }
835 }
836
837 #[must_use]
848 #[inline(always)]
849 pub fn child_count(&self, parent: NodeId) -> usize {
850 let idx: usize = parent.as_usize();
851 let Some(meta) = self.get_meta().get(idx) else {
852 return 0;
853 };
854 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
855 || meta.get_generation() != parent.get_generation()
856 {
857 return 0;
858 }
859 self.get_topology()[idx].get_child_count() as usize
860 }
861
862 #[must_use]
873 #[inline(always)]
874 pub fn has_children(&self, parent: NodeId) -> bool {
875 self.child_count(parent) > 0
876 }
877
878 #[must_use]
889 #[inline(always)]
890 pub fn first_child(&self, parent: NodeId) -> Option<NodeId> {
891 let idx: usize = parent.as_usize();
892 let meta: &NodeMeta = self.get_meta().get(idx)?;
893 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
894 || meta.get_generation() != parent.get_generation()
895 {
896 return None;
897 }
898 let first: u32 = self.get_topology()[idx].get_first_child();
899 if first == NODE_INDEX_NONE {
900 None
901 } else {
902 Some(NodeId::new(
903 first,
904 self.get_meta()[first as usize].get_generation(),
905 ))
906 }
907 }
908
909 #[must_use]
920 #[inline(always)]
921 pub fn last_child(&self, parent: NodeId) -> Option<NodeId> {
922 let idx: usize = parent.as_usize();
923 let meta: &NodeMeta = self.get_meta().get(idx)?;
924 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
925 || meta.get_generation() != parent.get_generation()
926 {
927 return None;
928 }
929 let last: u32 = self.get_topology()[idx].get_last_child();
930 if last == NODE_INDEX_NONE {
931 None
932 } else {
933 Some(NodeId::new(
934 last,
935 self.get_meta()[last as usize].get_generation(),
936 ))
937 }
938 }
939
940 #[must_use]
951 #[inline(always)]
952 pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
953 let idx: usize = id.as_usize();
954 let meta: &NodeMeta = self.get_meta().get(idx)?;
955 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
956 {
957 return None;
958 }
959 let next: u32 = self.get_topology()[idx].get_next_sibling();
960 if next == NODE_INDEX_NONE {
961 None
962 } else {
963 Some(NodeId::new(
964 next,
965 self.get_meta()[next as usize].get_generation(),
966 ))
967 }
968 }
969
970 #[must_use]
981 #[inline(always)]
982 pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
983 let idx: usize = id.as_usize();
984 let meta: &NodeMeta = self.get_meta().get(idx)?;
985 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
986 {
987 return None;
988 }
989 let prev: u32 = self.get_topology()[idx].get_prev_sibling();
990 if prev == NODE_INDEX_NONE {
991 None
992 } else {
993 Some(NodeId::new(
994 prev,
995 self.get_meta()[prev as usize].get_generation(),
996 ))
997 }
998 }
999
1000 #[must_use]
1011 pub fn children_vec(&self, parent: NodeId) -> Vec<NodeId> {
1012 self.children_iter(parent).collect()
1013 }
1014
1015 #[must_use]
1027 pub fn is_in_subtree(&self, candidate: NodeId, root: NodeId) -> bool {
1028 if candidate == root {
1029 return true;
1030 }
1031 let mut cursor_idx: usize = candidate.as_usize();
1032 let Some(start_meta) = self.get_meta().get(cursor_idx) else {
1033 return false;
1034 };
1035 if (start_meta.get_flags() & NODE_FLAG_ALIVE) == 0
1036 || start_meta.get_generation() != candidate.get_generation()
1037 {
1038 return false;
1039 }
1040 let root_idx: u32 = root.get_index();
1041 let root_gen: u32 = root.get_generation();
1042 let max_hops: usize = self.get_topology().len();
1043 let mut hops: usize = 0;
1044 while hops < max_hops {
1045 let parent_idx: u32 = self.get_topology()[cursor_idx].get_parent();
1046 if parent_idx == NODE_INDEX_NONE {
1047 return false;
1048 }
1049 if parent_idx == root_idx
1050 && self.get_meta()[parent_idx as usize].get_generation() == root_gen
1051 {
1052 return true;
1053 }
1054 cursor_idx = parent_idx as usize;
1055 hops += 1;
1056 }
1057 false
1058 }
1059
1060 fn recompute_nonzero_z_child(&mut self, parent_idx: usize) {
1067 let mut any_nonzero: bool = false;
1068 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1069 while cur != NODE_INDEX_NONE {
1070 let ci: usize = cur as usize;
1071 if self.get_nodes()[ci].layout_ref().get_z_index() != 0 {
1072 any_nonzero = true;
1073 break;
1074 }
1075 cur = self.get_topology()[ci].get_next_sibling();
1076 }
1077 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1078 let next: u16 = if any_nonzero {
1079 meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD
1080 } else {
1081 meta.get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD
1082 };
1083 let _: &mut NodeMeta = meta.set_flags(next);
1084 }
1085 }
1086
1087 fn sync_parent_nonzero_z(&mut self, parent_idx: usize, prev_z: i32, next_z: i32) {
1096 if next_z != 0 {
1097 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1098 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1099 let _: &mut NodeMeta = meta.set_flags(next);
1100 }
1101 } else if prev_z != 0 {
1102 self.recompute_nonzero_z_child(parent_idx);
1103 }
1104 }
1105
1106 fn unlink_child_at(&mut self, parent_idx: usize, child_idx: usize) {
1114 let child_topo: NodeTopology = self.get_topology()[child_idx];
1115 if child_topo.get_parent() != parent_idx as u32 {
1116 return;
1117 }
1118 let prev: u32 = child_topo.get_prev_sibling();
1119 let next: u32 = child_topo.get_next_sibling();
1120 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1121 if prev != NODE_INDEX_NONE {
1122 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(next);
1123 } else {
1124 let _: &mut NodeTopology = topo[parent_idx].set_first_child(next);
1125 }
1126 if next != NODE_INDEX_NONE {
1127 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(prev);
1128 } else {
1129 let _: &mut NodeTopology = topo[parent_idx].set_last_child(prev);
1130 }
1131 let next_count: u32 = topo[parent_idx].get_child_count().saturating_sub(1);
1132 let _: &mut NodeTopology = topo[parent_idx].set_child_count(next_count);
1133 let _: &mut NodeTopology = topo[child_idx]
1134 .set_parent(NODE_INDEX_NONE)
1135 .set_prev_sibling(NODE_INDEX_NONE)
1136 .set_next_sibling(NODE_INDEX_NONE);
1137 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(None);
1138 let child_z: i32 = self.get_nodes()[child_idx].layout_ref().get_z_index();
1139 if child_z != 0 {
1140 self.recompute_nonzero_z_child(parent_idx);
1141 }
1142 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1143 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1144 }
1145
1146 fn link_child_tail_at(&mut self, parent_idx: usize, parent_id: NodeId, child_idx: usize) {
1155 let child_u32: u32 = child_idx as u32;
1156 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1157 let tail: u32 = topo[parent_idx].get_last_child();
1158 let _: &mut NodeTopology = topo[child_idx]
1159 .set_parent(parent_idx as u32)
1160 .set_prev_sibling(tail)
1161 .set_next_sibling(NODE_INDEX_NONE);
1162 if tail != NODE_INDEX_NONE {
1163 let _: &mut NodeTopology = topo[tail as usize].set_next_sibling(child_u32);
1164 } else {
1165 let _: &mut NodeTopology = topo[parent_idx].set_first_child(child_u32);
1166 }
1167 let next_count: u32 = topo[parent_idx].get_child_count().saturating_add(1);
1168 let _: &mut NodeTopology = topo[parent_idx]
1169 .set_last_child(child_u32)
1170 .set_child_count(next_count);
1171 let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(Some(parent_id));
1172 if self.get_nodes()[child_idx].layout_ref().get_z_index() != 0 {
1173 let next_flags: u16 =
1174 self.get_meta()[parent_idx].get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1175 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(next_flags);
1176 }
1177 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1178 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1179 }
1180
1181 fn unlink_all_children_at(&mut self, parent_idx: usize) {
1188 let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1189 let _: &mut NodeTopology = self.get_mut_topology()[parent_idx]
1190 .set_first_child(NODE_INDEX_NONE)
1191 .set_last_child(NODE_INDEX_NONE)
1192 .set_child_count(0);
1193 let cleared: u16 = self.get_meta()[parent_idx].get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD;
1194 let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(cleared);
1195 while cur != NODE_INDEX_NONE {
1196 let ci: usize = cur as usize;
1197 let next: u32 = self.get_topology()[ci].get_next_sibling();
1198 let _: &mut NodeTopology = self.get_mut_topology()[ci]
1199 .set_parent(NODE_INDEX_NONE)
1200 .set_prev_sibling(NODE_INDEX_NONE)
1201 .set_next_sibling(NODE_INDEX_NONE);
1202 let _: &mut SceneNode = self.get_mut_nodes()[ci].set_parent(None);
1203 cur = next;
1204 }
1205 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1206 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1207 }
1208
1209 pub fn set_children_detached(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
1221 if self.get_node(parent).is_none() {
1222 return false;
1223 }
1224 if self.child_count(parent) == new_children.len()
1225 && self.children_iter(parent).eq(new_children.iter().copied())
1226 {
1227 return false;
1228 }
1229 self.clear_subtree_hover(parent);
1230 let parent_idx: usize = parent.as_usize();
1231 self.unlink_all_children_at(parent_idx);
1232 for child in new_children.iter().copied() {
1233 if child == parent || self.get_node(child).is_none() {
1234 continue;
1235 }
1236 let child_idx: usize = child.as_usize();
1237 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1238 if prev_parent != NODE_INDEX_NONE {
1239 self.unlink_child_at(prev_parent as usize, child_idx);
1240 }
1241 self.link_child_tail_at(parent_idx, parent, child_idx);
1242 }
1243 let dirty_lay: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1244 let dirty_child: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
1245 self.mark_dirty(parent, dirty_lay | dirty_child);
1246 true
1247 }
1248
1249 pub fn replace_child(&mut self, parent: NodeId, old_child: NodeId, new_child: NodeId) -> bool {
1262 if old_child == new_child || new_child == parent {
1263 return false;
1264 }
1265 if self.get_node(parent).is_none()
1266 || self.get_node(old_child).is_none()
1267 || self.get_node(new_child).is_none()
1268 {
1269 return false;
1270 }
1271 let parent_idx: usize = parent.as_usize();
1272 let old_idx: usize = old_child.as_usize();
1273 let new_idx: usize = new_child.as_usize();
1274 if self.get_topology()[old_idx].get_parent() != parent_idx as u32 {
1275 return false;
1276 }
1277 self.clear_subtree_hover(old_child);
1278 let prev_parent: u32 = self.get_topology()[new_idx].get_parent();
1279 if prev_parent != NODE_INDEX_NONE {
1280 self.unlink_child_at(prev_parent as usize, new_idx);
1281 }
1282 let old_topo: NodeTopology = self.get_topology()[old_idx];
1283 let prev: u32 = old_topo.get_prev_sibling();
1284 let next: u32 = old_topo.get_next_sibling();
1285 let new_u32: u32 = new_idx as u32;
1286 let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1287 if prev != NODE_INDEX_NONE {
1288 let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(new_u32);
1289 } else {
1290 let _: &mut NodeTopology = topo[parent_idx].set_first_child(new_u32);
1291 }
1292 if next != NODE_INDEX_NONE {
1293 let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(new_u32);
1294 } else {
1295 let _: &mut NodeTopology = topo[parent_idx].set_last_child(new_u32);
1296 }
1297 let _: &mut NodeTopology = topo[new_idx]
1298 .set_parent(parent_idx as u32)
1299 .set_prev_sibling(prev)
1300 .set_next_sibling(next);
1301 let _: &mut NodeTopology = topo[old_idx]
1302 .set_parent(NODE_INDEX_NONE)
1303 .set_prev_sibling(NODE_INDEX_NONE)
1304 .set_next_sibling(NODE_INDEX_NONE);
1305 let _: &mut SceneNode = self.get_mut_nodes()[old_idx].set_parent(None);
1306 let _: &mut SceneNode = self.get_mut_nodes()[new_idx].set_parent(Some(parent));
1307 let old_z: i32 = self.get_nodes()[old_idx].layout_ref().get_z_index();
1308 let new_z: i32 = self.get_nodes()[new_idx].layout_ref().get_z_index();
1309 self.sync_parent_nonzero_z(parent_idx, old_z, new_z);
1310 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1311 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1312 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1313 true
1314 }
1315
1316 pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
1328 let is_portal: bool = matches!(kind, NodeKind::Portal)
1329 || style.layout_ref().get_position() == Position::Fixed;
1330 let is_scroll: bool = matches!(kind, NodeKind::ScrollView)
1331 || style.layout_ref().get_overflow() == Overflow::Scroll;
1332 let mut init_flags: u16 = NODE_FLAG_ALIVE;
1333 if is_portal {
1334 init_flags |= NODE_FLAG_IS_PORTAL;
1335 }
1336 if is_scroll {
1337 init_flags |= NODE_FLAG_IS_SCROLL_CONTAINER;
1338 }
1339 let effect_entry: PaintEffectEntry =
1340 PaintEffectEntry::from_paint_and_blur(style.paint_ref(), 0.0);
1341 let effect_id: u32 = self.get_mut_effect_table().insert(effect_entry);
1342 let compact_paint: CompactPaintStyle =
1343 CompactPaintStyle::from_paint(style.paint_ref(), effect_id);
1344 let init_sigs: (u64, u64) = compute_style_sigs(&style);
1345 let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
1346 let slot_idx: usize = index as usize;
1347 let slot: &mut SceneNode = &mut self.get_mut_nodes()[slot_idx];
1348 let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
1349 *slot = SceneNode::new(next_gen, kind, style);
1350 self.get_mut_meta()[slot_idx] = NodeMeta::new(next_gen, init_flags, DIRTY_ALL);
1351 self.get_mut_topology()[slot_idx] = NodeTopology::default();
1352 self.get_mut_compact_paints()[slot_idx] = compact_paint;
1353 if let Some(ep) = self.get_mut_paint_epochs().get_mut(slot_idx) {
1354 *ep = ep.wrapping_add(1);
1355 }
1356 if let Some(ep) = self.get_mut_node_mutation_epochs().get_mut(slot_idx) {
1357 *ep = ep.wrapping_add(1).max(1);
1358 }
1359 if let Some(sigs) = self.get_mut_style_sigs().get_mut(slot_idx) {
1360 *sigs = init_sigs;
1361 }
1362 NodeId::new(index, next_gen)
1363 } else {
1364 let index: u32 = self.get_nodes().len() as u32;
1365 self.get_mut_nodes().push(SceneNode::new(1, kind, style));
1366 self.get_mut_meta()
1367 .push(NodeMeta::new(1, init_flags, DIRTY_ALL));
1368 self.get_mut_topology().push(NodeTopology::default());
1369 self.get_mut_compact_paints().push(compact_paint);
1370 self.get_mut_paint_epochs().push(0);
1371 self.get_mut_node_mutation_epochs().push(1);
1372 self.get_mut_style_sigs().push(init_sigs);
1373 NodeId::new(index, 1)
1374 };
1375 if is_portal {
1376 self.get_mut_portal_nodes().push(id);
1377 self.set_full_damage_pending(true);
1378 self.clear_dirty_paint_queue();
1379 }
1380 if is_scroll {
1381 self.get_mut_scroll_nodes().push(id);
1382 }
1383 let next_live: usize = self.get_live_count().saturating_add(1);
1384 self.set_live_count(next_live);
1385 let next_created: usize = self.get_created_since_damage().saturating_add(1);
1386 self.set_created_since_damage(next_created);
1387 let next_topo_rev: u64 = self.get_topology_revision().wrapping_add(1);
1388 let _: &mut Self = self.set_topology_revision(next_topo_rev);
1389 self.set_layout_damage_pending(true);
1390 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
1391 if next_created > DIRTY_PAINT_FULL_THRESHOLD {
1392 self.set_full_damage_pending(true);
1393 self.set_full_damage_overflow(true);
1394 self.clear_dirty_paint_queue();
1395 } else if !self.get_full_damage_pending() {
1396 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1397 self.set_full_damage_pending(true);
1398 self.set_full_damage_overflow(true);
1399 self.clear_dirty_paint_queue();
1400 } else {
1401 self.get_mut_dirty_paint_nodes().push(id);
1402 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1403 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
1404 let _: &mut NodeMeta = meta.set_flags(next_flags);
1405 }
1406 }
1407 }
1408 let next_rev: u64 = self.get_revision().wrapping_add(1);
1409 self.set_revision(next_rev);
1410 notify_frame_needed();
1411 id
1412 }
1413
1414 pub fn create_view(&mut self, style: Style) -> NodeId {
1425 self.create_node(NodeKind::View, style)
1426 }
1427
1428 pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
1440 self.create_node(NodeKind::Text(content), style)
1441 }
1442
1443 pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1455 self.create_node(NodeKind::Input(state), style)
1456 }
1457
1458 pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1470 self.create_node(NodeKind::Image(buffer), style)
1471 }
1472
1473 pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
1484 self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
1485 }
1486
1487 pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
1499 self.create_canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
1500 }
1501
1502 pub fn create_canvas_with_caching(
1515 &mut self,
1516 style: Style,
1517 caching: CanvasCaching,
1518 painter: CanvasDrawCallback,
1519 ) -> NodeId {
1520 let id: NodeId = self.create_node(NodeKind::Canvas(caching), style);
1521 if let Some(node) = self.get_node_mut(id) {
1522 node.set_canvas_painter(Some(painter));
1523 }
1524 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1525 let next: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
1526 let _: &mut NodeMeta = meta.set_flags(next);
1527 }
1528 id
1529 }
1530
1531 pub fn create_portal(&mut self, style: Style) -> NodeId {
1542 self.create_node(NodeKind::Portal, style)
1543 }
1544
1545 pub fn create_fragment(&mut self) -> NodeId {
1555 self.create_node(NodeKind::Fragment, Style::default())
1556 }
1557
1558 #[must_use]
1569 pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
1570 let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
1571 if node.get_alive() && node.get_generation() == id.get_generation() {
1572 Some(node)
1573 } else {
1574 None
1575 }
1576 }
1577
1578 pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
1589 let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
1590 if node.get_alive() && node.get_generation() == id.get_generation() {
1591 Some(node)
1592 } else {
1593 None
1594 }
1595 }
1596
1597 #[must_use]
1607 #[inline(always)]
1608 pub fn live_node_count(&self) -> usize {
1609 self.get_live_count()
1610 }
1611
1612 pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
1620 if parent == child || self.get_node(parent).is_none() || self.get_node(child).is_none() {
1621 return;
1622 }
1623 let parent_idx: usize = parent.as_usize();
1624 let child_idx: usize = child.as_usize();
1625 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1626 if let Some(old_parent) = prev_parent {
1627 if old_parent != parent {
1628 self.record_subtree_logical_damage(child);
1629 }
1630 self.unlink_child_at(old_parent.as_usize(), child_idx);
1631 if old_parent != parent {
1632 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1633 }
1634 }
1635 self.link_child_tail_at(parent_idx, parent, child_idx);
1636 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1637 }
1638
1639 pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
1647 if children.is_empty() || self.get_node(parent).is_none() {
1648 return;
1649 }
1650 let parent_idx: usize = parent.as_usize();
1651 let mut attached_any: bool = false;
1652 for child in children.iter().copied() {
1653 if child == parent || self.get_node(child).is_none() {
1654 continue;
1655 }
1656 let child_idx: usize = child.as_usize();
1657 let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1658 if let Some(old_parent) = prev_parent {
1659 if old_parent != parent {
1660 self.record_subtree_logical_damage(child);
1661 }
1662 self.unlink_child_at(old_parent.as_usize(), child_idx);
1663 if old_parent != parent {
1664 self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1665 }
1666 }
1667 self.link_child_tail_at(parent_idx, parent, child_idx);
1668 attached_any = true;
1669 }
1670 if attached_any {
1671 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1672 }
1673 }
1674
1675 pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
1683 if self.get_node(parent).is_none() {
1684 return;
1685 }
1686 let parent_idx: usize = parent.as_usize();
1687 let old_children: Vec<NodeId> = self.children_vec(parent);
1688 self.unlink_all_children_at(parent_idx);
1689 if new_children.is_empty() {
1690 for old_child in old_children.into_iter() {
1691 self.dispose_subtree(old_child);
1692 }
1693 } else if old_children.len() > 16 && new_children.len() > 16 {
1694 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1695 for old_child in old_children.into_iter() {
1696 if !keep_set.contains(&old_child) {
1697 self.dispose_subtree(old_child);
1698 }
1699 }
1700 } else {
1701 for old_child in old_children.into_iter() {
1702 if !new_children.contains(&old_child) {
1703 self.dispose_subtree(old_child);
1704 }
1705 }
1706 }
1707 for child in new_children.into_iter() {
1708 if child == parent || self.get_node(child).is_none() {
1709 continue;
1710 }
1711 let child_idx: usize = child.as_usize();
1712 let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1713 if prev_parent != NODE_INDEX_NONE {
1714 self.unlink_child_at(prev_parent as usize, child_idx);
1715 }
1716 self.link_child_tail_at(parent_idx, parent, child_idx);
1717 }
1718 self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1719 }
1720
1721 #[inline]
1732 fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
1733 let same_static: bool = prev.background_color() == next.background_color()
1734 && prev.background_gradient() == next.background_gradient()
1735 && prev.get_border() == next.get_border()
1736 && prev.get_radius() == next.get_radius()
1737 && prev.box_shadow() == next.box_shadow()
1738 && prev.focus_ring_border() == next.focus_ring_border()
1739 && prev.get_cursor() == next.get_cursor()
1740 && prev.get_pointer_events() == next.get_pointer_events();
1741 let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
1742 let composite_changed: bool = prev.get_transform() != next.get_transform()
1743 || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
1744 same_static && same_vis && composite_changed
1745 }
1746
1747 #[inline]
1759 fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
1760 let layout_changed: bool = prev.layout_ref() != next.layout_ref();
1761 let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
1762 if layout_changed || text_metrics_changed {
1763 let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
1764 let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
1765 let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
1766 Some(next_fixed)
1767 } else {
1768 None
1769 };
1770 let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1771 let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
1772 let mask: u16 = layout_bits | visual_bits;
1773 return (mask, portal_update);
1774 }
1775 let paint_changed: bool = prev.paint_ref() != next.paint_ref();
1776 let text_visual_changed: bool = prev.text_ref() != next.text_ref();
1777 if paint_changed && !text_visual_changed {
1778 if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
1779 return (DIRTY_COMPOSITE, None);
1780 }
1781 return (DIRTY_PAINT, None);
1782 }
1783 if paint_changed || text_visual_changed {
1784 (DIRTY_PAINT, None)
1785 } else {
1786 (DIRTY_NONE, None)
1787 }
1788 }
1789
1790 #[inline]
1801 fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
1802 let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
1803 let transform_changed: bool = prev.get_transform() != next.get_transform();
1804 let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
1805 let focus_removed: bool =
1806 prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
1807 let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
1808 let flag_value: bool = shadow_changed || transform_changed;
1809 let is_matched: bool = border_shrank || focus_removed;
1810 let ab: bool = flag_value || is_matched;
1811 ab || opacity_toggled_zero
1812 }
1813
1814 pub fn set_style(&mut self, id: NodeId, style: Style) {
1822 let has_children: bool = self.has_children(id);
1823 let Some(node) = self.get_node(id) else {
1824 return;
1825 };
1826 let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
1827 let is_scroll_kind: bool = matches!(node.get_kind(), NodeKind::ScrollView);
1828 let prev: &Style = node.style_ref();
1829 let (dirty_mask, portal_update): (u16, Option<bool>) =
1830 Self::diff_style_change(prev, &style, is_portal_kind);
1831 if dirty_mask == DIRTY_NONE {
1832 return;
1833 }
1834 let prev_scroll: bool =
1835 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1836 let next_scroll: bool =
1837 is_scroll_kind || style.layout_ref().get_overflow() == Overflow::Scroll;
1838 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1839 Some(next_scroll)
1840 } else {
1841 None
1842 };
1843 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
1844 let subtree_hidden: bool = pre_paint
1845 && (prev.paint_ref().get_opacity() > 0.0) != (style.paint_ref().get_opacity() > 0.0)
1846 && has_children;
1847 let prev_z: i32 = prev.layout_ref().get_z_index();
1848 let parent_idx: u32 = self.get_topology()[id.as_usize()].get_parent();
1849 if subtree_hidden {
1850 self.record_subtree_logical_damage(id);
1851 } else if pre_paint {
1852 self.record_node_logical_damage(id);
1853 }
1854 let hiding_now: bool = style.layout_ref().get_display() == Display::None
1855 || style.paint_ref().get_opacity() <= 0.001
1856 || style.paint_ref().get_pointer_events() == PointerEvents::None;
1857 let next_z: i32 = style.layout_ref().get_z_index();
1858 let next_paint: PaintStyle = *style.paint_ref();
1859 if let Some(node) = self.get_node_mut(id) {
1860 node.set_style(style);
1861 }
1862 let blur: f32 = self.backdrop_blur_radius(id);
1863 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1864 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1865 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1866 }
1867 if hiding_now {
1868 self.clear_subtree_hover(id);
1869 }
1870 if let Some(is_portal) = portal_update {
1871 self.sync_portal_registration(id, is_portal);
1872 }
1873 if let Some(is_scroll) = scroll_update {
1874 self.sync_scroll_registration(id, is_scroll);
1875 }
1876 self.mark_dirty(id, dirty_mask);
1877 }
1878
1879 pub fn mutate_style<CallbackFn>(&mut self, id: NodeId, mutator: CallbackFn) -> bool
1891 where
1892 CallbackFn: FnOnce(&mut Style),
1893 {
1894 let has_children: bool = self.has_children(id);
1895 let prev_opt: Option<(Style, bool, bool, u32)> =
1896 self.get_node(id).map(|node: &SceneNode| {
1897 (
1898 *node.style_ref(),
1899 matches!(node.get_kind(), NodeKind::Portal),
1900 matches!(node.get_kind(), NodeKind::ScrollView),
1901 self.get_topology()[id.as_usize()].get_parent(),
1902 )
1903 });
1904 let Some((prev, is_portal_kind, is_scroll_kind, parent_idx)) = prev_opt else {
1905 return false;
1906 };
1907 let mut next: Style = prev;
1908 mutator(&mut next);
1909 let (dirty_mask, portal_update): (u16, Option<bool>) =
1910 Self::diff_style_change(&prev, &next, is_portal_kind);
1911 if dirty_mask == DIRTY_NONE {
1912 return false;
1913 }
1914 let prev_scroll: bool =
1915 is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1916 let next_scroll: bool =
1917 is_scroll_kind || next.layout_ref().get_overflow() == Overflow::Scroll;
1918 let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1919 Some(next_scroll)
1920 } else {
1921 None
1922 };
1923 let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
1924 if pre_paint {
1925 let opacity_toggled_zero: bool =
1926 (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
1927 if opacity_toggled_zero && has_children {
1928 self.record_subtree_logical_damage(id);
1929 } else {
1930 self.record_node_logical_damage(id);
1931 }
1932 }
1933 let hiding_now: bool = next.layout_ref().get_display() == Display::None
1934 || next.paint_ref().get_opacity() <= 0.001
1935 || next.paint_ref().get_pointer_events() == PointerEvents::None;
1936 let prev_z: i32 = prev.layout_ref().get_z_index();
1937 let next_z: i32 = next.layout_ref().get_z_index();
1938 let next_paint: PaintStyle = *next.paint_ref();
1939 if let Some(node) = self.get_node_mut(id) {
1940 node.set_style(next);
1941 }
1942 let blur: f32 = self.backdrop_blur_radius(id);
1943 self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1944 if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1945 self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1946 }
1947 if hiding_now {
1948 self.clear_subtree_hover(id);
1949 }
1950 if let Some(is_portal) = portal_update {
1951 self.sync_portal_registration(id, is_portal);
1952 }
1953 if let Some(is_scroll) = scroll_update {
1954 self.sync_scroll_registration(id, is_scroll);
1955 }
1956 self.mark_dirty(id, dirty_mask);
1957 true
1958 }
1959
1960 #[must_use]
1970 fn has_definite_text_box(layout: &LayoutStyle) -> bool {
1971 matches!(
1972 layout.get_width(),
1973 Length::Px(_)
1974 | Length::Percent(_)
1975 | Length::ViewportWidth(_)
1976 | Length::ViewportHeight(_)
1977 ) && matches!(
1978 layout.get_height(),
1979 Length::Px(_)
1980 | Length::Percent(_)
1981 | Length::ViewportWidth(_)
1982 | Length::ViewportHeight(_)
1983 ) && layout.get_overflow() != Overflow::Scroll
1984 }
1985
1986 pub fn set_text(&mut self, id: NodeId, text: String) {
1994 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1995 Some(node) => {
1996 let layout: &LayoutStyle = node.style_ref().layout_ref();
1997 let has_fixed: bool = Self::has_definite_text_box(layout);
1998 match node.get_mut_kind() {
1999 NodeKind::Text(current) => {
2000 if *current == text {
2001 (false, has_fixed)
2002 } else {
2003 *current = text;
2004 (true, has_fixed)
2005 }
2006 }
2007 _ => (false, false),
2008 }
2009 }
2010 None => (false, false),
2011 };
2012 if changed {
2013 let mask: u16 = if fixed_size {
2014 DIRTY_PAINT
2015 } else {
2016 DIRTY_TEXT_CHANGE_MASK
2017 };
2018 self.mark_dirty(id, mask);
2019 }
2020 }
2021
2022 pub fn set_image(&mut self, id: NodeId, buffer: ImageBuffer) {
2030 let changed: bool = match self.get_node_mut(id) {
2031 Some(node) => {
2032 let same: bool = match node.get_mut_kind() {
2033 NodeKind::Image(existing) => *existing == buffer,
2034 _ => false,
2035 };
2036 if same {
2037 false
2038 } else {
2039 *node.get_mut_kind() = NodeKind::Image(buffer);
2040 true
2041 }
2042 }
2043 None => false,
2044 };
2045 if changed {
2046 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2047 self.mark_dirty(id, dirty_l | DIRTY_PAINT);
2048 notify_frame_needed();
2049 }
2050 }
2051
2052 pub fn set_text_str(&mut self, id: NodeId, text: &str) {
2060 let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2061 Some(node) => {
2062 let layout: &LayoutStyle = node.style_ref().layout_ref();
2063 let has_fixed: bool = Self::has_definite_text_box(layout);
2064 match node.get_mut_kind() {
2065 NodeKind::Text(current) => {
2066 if current.as_str() == text {
2067 (false, has_fixed)
2068 } else {
2069 current.clear();
2070 current.push_str(text);
2071 (true, has_fixed)
2072 }
2073 }
2074 _ => (false, false),
2075 }
2076 }
2077 None => (false, false),
2078 };
2079 if changed {
2080 let mask: u16 = if fixed_size {
2081 DIRTY_PAINT
2082 } else {
2083 DIRTY_TEXT_CHANGE_MASK
2084 };
2085 self.mark_dirty(id, mask);
2086 }
2087 }
2088
2089 pub fn mutate_text<CallbackFn>(&mut self, id: NodeId, mutate: CallbackFn)
2097 where
2098 CallbackFn: FnOnce(&mut String),
2099 {
2100 let (updated, fixed_size): (bool, bool) = match self.get_node_mut(id) {
2101 Some(node) => {
2102 let layout: &LayoutStyle = node.style_ref().layout_ref();
2103 let has_fixed: bool = Self::has_definite_text_box(layout);
2104 match node.get_mut_kind() {
2105 NodeKind::Text(current) => {
2106 mutate(current);
2107 (true, has_fixed)
2108 }
2109 _ => (false, false),
2110 }
2111 }
2112 None => (false, false),
2113 };
2114 if updated {
2115 let mask: u16 = if fixed_size {
2116 DIRTY_PAINT
2117 } else {
2118 DIRTY_TEXT_CHANGE_MASK
2119 };
2120 self.mark_dirty(id, mask);
2121 }
2122 }
2123
2124 pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
2132 let changed: bool = match self.get_node_mut(id) {
2133 Some(node) => {
2134 let layout_box: LayoutBox = node.get_layout_box();
2135 let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
2136 && layout_box.get_content_size().get_height() <= 0.0
2137 && layout_box.get_content_bounds().get_width() <= 0.0
2138 && layout_box.get_content_bounds().get_height() <= 0.0;
2139 let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
2140 Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
2141 } else {
2142 let max_x: f32 = (layout_box.get_content_size().get_width()
2143 - layout_box.get_content_bounds().get_width())
2144 .max(0.0);
2145 let max_y: f32 = (layout_box.get_content_size().get_height()
2146 - layout_box.get_content_bounds().get_height())
2147 .max(0.0);
2148 Point::new(
2149 offset.get_x().clamp(0.0, max_x),
2150 offset.get_y().clamp(0.0, max_y),
2151 )
2152 };
2153 if layout_box.get_scroll_offset() == clamped {
2154 false
2155 } else {
2156 node.get_mut_layout_box().set_scroll_offset(clamped);
2157 true
2158 }
2159 }
2160 None => false,
2161 };
2162 if changed {
2163 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2164 }
2165 }
2166
2167 pub fn request_scroll_into_view(&mut self, target: NodeId) {
2174 if self.live_generation(target).is_none() {
2175 return;
2176 }
2177 let target_parent: Option<NodeId> = self.get_node(target).and_then(SceneNode::parent_id);
2178 let mut retained: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2179 retained.retain(|existing: &NodeId| {
2180 *existing != target
2181 && self.live_generation(*existing).is_some()
2182 && (target_parent.is_none()
2183 || self.get_node(*existing).and_then(SceneNode::parent_id) != target_parent)
2184 });
2185 retained.push(target);
2186 let _: &mut Self = self.set_pending_scroll_into_view(retained);
2187 self.mark_dirty(target, DIRTY_COMPOSITE);
2188 }
2189
2190 pub fn flush_scroll_into_view_requests(&mut self) -> bool {
2202 if self.get_pending_scroll_into_view().is_empty() {
2203 return false;
2204 }
2205 let requests: Vec<NodeId> = take(self.get_mut_pending_scroll_into_view());
2206 let mut any_scrolled: bool = false;
2207 for target in requests.into_iter() {
2208 if self.live_generation(target).is_none() {
2209 continue;
2210 }
2211 if !self.is_node_visible(target) {
2212 self.get_mut_pending_scroll_into_view().push(target);
2213 continue;
2214 }
2215 let Some(target_node) = self.get_node(target) else {
2216 continue;
2217 };
2218 let target_raw: Rect = target_node.get_layout_box().get_bounds();
2219 if target_raw.get_height() <= 0.0 && target_raw.get_width() <= 0.0 {
2220 self.get_mut_pending_scroll_into_view().push(target);
2221 continue;
2222 }
2223 let mut scroll_ancestor: Option<NodeId> = None;
2224 let mut cursor: Option<NodeId> = target_node.parent_id();
2225 while let Some(parent_id) = cursor {
2226 if let Some(parent_node) = self.get_node(parent_id) {
2227 if matches!(parent_node.get_kind(), NodeKind::ScrollView)
2228 || parent_node.style_ref().layout_ref().get_overflow() == Overflow::Scroll
2229 {
2230 scroll_ancestor = Some(parent_id);
2231 break;
2232 }
2233 cursor = parent_node.parent_id();
2234 } else {
2235 break;
2236 }
2237 }
2238 let Some(scroll_id) = scroll_ancestor else {
2239 continue;
2240 };
2241 let Some(scroll_node) = self.get_node(scroll_id) else {
2242 continue;
2243 };
2244 let scroll_box: LayoutBox = scroll_node.get_layout_box();
2245 let view_rect: Rect = scroll_box.get_content_bounds();
2246 if view_rect.get_height() <= 1.0 {
2247 self.get_mut_pending_scroll_into_view().push(target);
2248 continue;
2249 }
2250 let current_scroll: Point = scroll_box.get_scroll_offset();
2251 let visible_top: f32 = target_raw.get_y() - current_scroll.get_y();
2252 let visible_bottom: f32 = target_raw.bottom() - current_scroll.get_y();
2253 if visible_top < view_rect.get_y() || visible_bottom > view_rect.bottom() {
2254 let offset_in_content: f32 = target_raw.get_y() - view_rect.get_y();
2255 let centered_scroll_y: f32 = offset_in_content
2256 - (view_rect.get_height() - target_raw.get_height()).max(0.0) * 0.5;
2257 let before_offset: Point = current_scroll;
2258 self.set_scroll_offset(
2259 scroll_id,
2260 Point::new(current_scroll.get_x(), centered_scroll_y),
2261 );
2262 let after_offset: Point = self
2263 .get_node(scroll_id)
2264 .map(|node_ref: &SceneNode| node_ref.get_layout_box().get_scroll_offset())
2265 .unwrap_or(before_offset);
2266 if after_offset != before_offset {
2267 any_scrolled = true;
2268 }
2269 }
2270 }
2271 any_scrolled
2272 }
2273
2274 pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
2283 let mut changed: bool = false;
2284 let mut prev_metrics: Option<(f32, f32)> = None;
2285 let next_metrics: (f32, f32) = (scroll_y.max(0.0), content_height.max(1.0));
2286 let mut scrollbar_bounds: Option<(Rect, f32, f32)> = None;
2287 if let Some(node) = self.get_node_mut(id) {
2288 let prev: Option<(f32, f32)> = node.virtual_scroll_metrics();
2289 prev_metrics = prev;
2290 let next: Option<(f32, f32)> = Some(next_metrics);
2291 if prev != next {
2292 changed = true;
2293 node.set_virtual_scroll(next);
2294 let raw_b: Rect = node.get_layout_box().get_bounds();
2295 let border_width: f32 = node.style_ref().paint_ref().get_border().get_width();
2296 let view_h: f32 = node
2297 .get_layout_box()
2298 .get_content_bounds()
2299 .get_height()
2300 .max(1.0);
2301 if raw_b.get_width() > 0.0 && raw_b.get_height() > 0.0 {
2302 scrollbar_bounds = Some((raw_b, border_width, view_h));
2303 }
2304 }
2305 }
2306 if changed {
2307 self.bump_node_mutation_epoch(id.as_usize());
2308 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2309 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
2310 let _: &mut NodeMeta = meta.set_flags(next_flags);
2311 }
2312 let show_scrollbar: bool = self
2313 .get_node(self.get_root())
2314 .map(|scene_node: &SceneNode| {
2315 let rb: Rect = scene_node.get_layout_box().get_bounds();
2316 rb.get_width().min(rb.get_height()) >= 540.0
2317 })
2318 .unwrap_or(true);
2319 if !show_scrollbar {
2320 let next_rev: u64 = self.get_revision().wrapping_add(1);
2321 self.set_revision(next_rev);
2322 } else if let Some((raw_b, bloom_width, view_h)) = scrollbar_bounds
2323 && let Some(screen_b) = self.node_screen_bounds(id)
2324 && screen_b.get_width() > 0.0
2325 && screen_b.get_height() > 0.0
2326 {
2327 let inner_y: f32 = screen_b.get_y() + bloom_width;
2328 let inner_h: f32 = (raw_b.get_height() - bloom_width * 2.0).max(1.0);
2329 let track_y: f32 = inner_y + 3.0;
2330 let track_h: f32 = (inner_h - 6.0).max(16.0);
2331 let n_max_sy: f32 = (next_metrics.1 - view_h).max(0.0);
2332 let n_ratio: f32 = (view_h / next_metrics.1.max(view_h)).clamp(0.0, 1.0);
2333 let n_thumb_h: f32 = (track_h * n_ratio).clamp(20.0_f32.min(track_h), track_h);
2334 let n_frac: f32 = if n_max_sy > 1.0 {
2335 (next_metrics.0 / n_max_sy).clamp(0.0, 1.0)
2336 } else {
2337 0.0
2338 };
2339 let ny0: f32 = track_y + (track_h - n_thumb_h) * n_frac;
2340 let ny1: f32 = ny0 + n_thumb_h;
2341 let (y0, y1): (f32, f32) = match prev_metrics {
2342 Some((py, ph)) => {
2343 let p_max_sy: f32 = (ph - view_h).max(0.0);
2344 let p_ratio: f32 = (view_h / ph.max(view_h)).clamp(0.0, 1.0);
2345 let p_thumb_h: f32 =
2346 (track_h * p_ratio).clamp(20.0_f32.min(track_h), track_h);
2347 let p_frac: f32 = if p_max_sy > 1.0 {
2348 (py / p_max_sy).clamp(0.0, 1.0)
2349 } else {
2350 0.0
2351 };
2352 let py0: f32 = track_y + (track_h - p_thumb_h) * p_frac;
2353 let py1: f32 = py0 + p_thumb_h;
2354 (py0.min(ny0) - 4.0, py1.max(ny1) + 4.0)
2355 }
2356 None => (screen_b.get_y(), screen_b.bottom()),
2357 };
2358 let clamped_y0: f32 = y0.max(screen_b.get_y());
2359 let clamped_y1: f32 = y1.min(screen_b.bottom());
2360 let strip_x: f32 = (screen_b.right() - bloom_width - 12.0).max(screen_b.get_x());
2361 let strip_w: f32 = (screen_b.right() - strip_x + 2.0).max(1.0);
2362 let strip_rect: Rect = Rect::new(
2363 strip_x,
2364 clamped_y0,
2365 strip_w,
2366 (clamped_y1 - clamped_y0).max(1.0),
2367 );
2368 if !self.get_full_damage_pending() {
2369 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2370 self.set_full_damage_pending(true);
2371 self.set_full_damage_overflow(true);
2372 self.get_mut_extra_logical_damage().clear();
2373 } else {
2374 self.get_mut_extra_logical_damage().push(strip_rect);
2375 }
2376 }
2377 let next_rev: u64 = self.get_revision().wrapping_add(1);
2378 self.set_revision(next_rev);
2379 } else {
2380 self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2381 }
2382 }
2383 }
2384
2385 #[must_use]
2395 pub fn active_webview_node(&self) -> Option<NodeId> {
2396 let Self {
2397 active_webview_node,
2398 ..
2399 } = self;
2400 *active_webview_node
2401 }
2402
2403 pub fn set_active_webview_node(&mut self, node: Option<NodeId>) {
2410 let Self {
2411 active_webview_node,
2412 ..
2413 } = self;
2414 *active_webview_node = node;
2415 }
2416
2417 #[must_use]
2428 pub fn node_effective_opacity(&self, id: NodeId) -> f32 {
2429 let mut combined_alpha: f32 = 1.0;
2430 let mut cursor: Option<NodeId> = Some(id);
2431 while let Some(node_id) = cursor {
2432 let Some(scene_node) = self.get_node(node_id) else {
2433 return 0.0;
2434 };
2435 let style: &Style = scene_node.style_ref();
2436 if style.layout_ref().get_display() == Display::None {
2437 return 0.0;
2438 }
2439 combined_alpha *= style.paint_ref().get_opacity().clamp(0.0, 1.0);
2440 if combined_alpha <= 0.001 {
2441 return 0.0;
2442 }
2443 cursor = scene_node.parent_id();
2444 }
2445 combined_alpha.clamp(0.0, 1.0)
2446 }
2447
2448 #[must_use]
2461 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
2462 let node: &SceneNode = self.get_node(id)?;
2463 let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
2464 match self.node_scroll_and_transform(node) {
2465 Some(vals) => vals,
2466 None => return Some(Rect::default()),
2467 };
2468 let raw: Rect = node.get_layout_box().get_bounds();
2469 Some(Rect::new(
2470 raw.get_x() - off.get_x() + tx,
2471 raw.get_y() - off.get_y() + ty,
2472 raw.get_width() * sx,
2473 raw.get_height() * sy,
2474 ))
2475 }
2476
2477 #[inline]
2488 fn node_scroll_and_transform(&self, node: &SceneNode) -> Option<(Point, f32, f32, f32, f32)> {
2489 let style: &Style = node.style_ref();
2490 if style.layout_ref().get_display() == Display::None {
2491 return None;
2492 }
2493 let transform_val: Transform2D = style.paint_ref().get_transform();
2494 let mut tx: f32 = transform_val.get_translate_x();
2495 let mut ty: f32 = transform_val.get_translate_y();
2496 let sx_scale: f32 = transform_val.get_scale_x();
2497 let sy_scale: f32 = transform_val.get_scale_y();
2498 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2499 || style.layout_ref().get_position() == Position::Fixed;
2500 let mut stop_transform: bool = false;
2501 let mut scroll_x: f32 = 0.0;
2502 let mut scroll_y: f32 = 0.0;
2503 let mut cursor: Option<NodeId> = node.parent_id();
2504 while let Some(pid) = cursor {
2505 if let Some(pnode) = self.get_node(pid) {
2506 let pstyle: &Style = pnode.style_ref();
2507 if pstyle.layout_ref().get_display() == Display::None {
2508 return None;
2509 }
2510 if !stop_transform {
2511 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2512 tx += ptr.get_translate_x();
2513 ty += ptr.get_translate_y();
2514 if !start_top_layer {
2515 let off: Point = pnode.get_layout_box().get_scroll_offset();
2516 scroll_x += off.get_x();
2517 scroll_y += off.get_y();
2518 }
2519 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2520 || pstyle.layout_ref().get_position() == Position::Fixed;
2521 if parent_top_layer {
2522 stop_transform = true;
2523 }
2524 }
2525 cursor = pnode.parent_id();
2526 } else {
2527 break;
2528 }
2529 }
2530 Some((Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale))
2531 }
2532
2533 #[must_use]
2546 pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
2547 let node: &SceneNode = self.get_node(id)?;
2548 let raw_bounds: Rect = node.get_layout_box().get_bounds();
2549 if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
2550 return Some(Rect::default());
2551 }
2552 let style: &Style = node.style_ref();
2553 let paint: &PaintStyle = style.paint_ref();
2554 let transform_val: Transform2D = paint.get_transform();
2555 if transform_val.get_rotation_rad().abs() > 0.0001
2556 || transform_val.get_scale_x() <= 0.0
2557 || transform_val.get_scale_y() <= 0.0
2558 {
2559 return None;
2560 }
2561 let border_w: f32 = paint.get_border().get_width();
2562 let focus_pad: f32 = if paint.focus_ring_border().is_some() {
2563 12.0
2564 } else {
2565 0.0
2566 };
2567 let mut margin: f32 = if border_w > 0.0 {
2568 10.0_f32.max(border_w + 6.0).max(focus_pad)
2569 } else {
2570 4.0_f32.max(focus_pad)
2571 };
2572 if let Some(shadow) = paint.box_shadow() {
2573 let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
2574 let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
2575 let spread: f32 = shadow.get_spread_radius().max(0.0);
2576 let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
2577 margin = margin.max(blur_pad + spread + off_max + 4.0);
2578 }
2579 let backdrop_blur: f32 = self.backdrop_blur_radius(id);
2580 if backdrop_blur > 0.0 {
2581 let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
2582 let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
2583 margin = margin.max(blur_halo);
2584 }
2585 let tx: f32 = transform_val.get_translate_x();
2586 let ty: f32 = transform_val.get_translate_y();
2587 let sx: f32 = transform_val.get_scale_x();
2588 let sy: f32 = transform_val.get_scale_y();
2589 let base_rect: Rect = Rect::new(
2590 raw_bounds.get_x() - margin,
2591 raw_bounds.get_y() - margin,
2592 raw_bounds.get_width() + margin * 2.0,
2593 raw_bounds.get_height() + margin * 2.0,
2594 );
2595 let shifted_x: bool = tx != 0.0 || sx != 1.0;
2596 let shifted_y: bool = ty != 0.0 || sy != 1.0;
2597 let mut cur_rect: Rect = if shifted_x || shifted_y {
2598 let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
2599 let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
2600 let shifted_rect: Rect = Rect::new(
2601 raw_bounds.get_x() + tx - margin - scale_pad_x,
2602 raw_bounds.get_y() + ty - margin - scale_pad_y,
2603 raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
2604 raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
2605 );
2606 base_rect.union(shifted_rect)
2607 } else {
2608 base_rect
2609 };
2610 let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2611 || style.layout_ref().get_position() == Position::Fixed;
2612 let mut cursor: Option<NodeId> = node.parent_id();
2613 while let Some(pid) = cursor {
2614 let Some(pnode) = self.get_node(pid) else {
2615 break;
2616 };
2617 let pstyle: &Style = pnode.style_ref();
2618 let ptr: Transform2D = pstyle.paint_ref().get_transform();
2619 if ptr.get_rotation_rad().abs() > 0.0001
2620 || (ptr.get_scale_x() - 1.0).abs() > 0.001
2621 || (ptr.get_scale_y() - 1.0).abs() > 0.001
2622 {
2623 return None;
2624 }
2625 if !start_top_layer {
2626 let off: Point = pnode.get_layout_box().get_scroll_offset();
2627 cur_rect = Rect::new(
2628 cur_rect.get_x() - off.get_x(),
2629 cur_rect.get_y() - off.get_y(),
2630 cur_rect.get_width(),
2631 cur_rect.get_height(),
2632 );
2633 let p_ov: Overflow = pstyle.layout_ref().get_overflow();
2634 if matches!(p_ov, Overflow::Hidden | Overflow::Scroll) {
2635 let pb: Rect = pnode.get_layout_box().get_bounds();
2636 if pb.get_width() > 0.0 && pb.get_height() > 0.0 {
2637 let clip_box: Rect = Rect::new(
2638 pb.get_x() - 1.0,
2639 pb.get_y() - 1.0,
2640 pb.get_width() + 2.0,
2641 pb.get_height() + 2.0,
2642 );
2643 match cur_rect.intersect(clip_box) {
2644 Some(clipped) => cur_rect = clipped,
2645 None => return Some(Rect::default()),
2646 }
2647 }
2648 }
2649 }
2650 let ptx: f32 = ptr.get_translate_x();
2651 let pty: f32 = ptr.get_translate_y();
2652 if ptx != 0.0 || pty != 0.0 {
2653 cur_rect = Rect::new(
2654 cur_rect.get_x() + ptx,
2655 cur_rect.get_y() + pty,
2656 cur_rect.get_width(),
2657 cur_rect.get_height(),
2658 );
2659 }
2660 let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2661 || pstyle.layout_ref().get_position() == Position::Fixed;
2662 if parent_top_layer {
2663 break;
2664 }
2665 cursor = pnode.parent_id();
2666 }
2667 Some(cur_rect)
2668 }
2669
2670 #[must_use]
2681 pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
2682 let x0: f32 = (logical.get_x() * scale).floor();
2683 let y0: f32 = (logical.get_y() * scale).floor();
2684 let x1: f32 = (logical.right() * scale).ceil();
2685 let y1: f32 = (logical.bottom() * scale).ceil();
2686 Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2687 }
2688
2689 fn record_node_logical_damage(&mut self, id: NodeId) {
2696 if self.get_full_damage_pending() {
2697 return;
2698 }
2699 let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
2700 match rect_opt {
2701 Some(rect) => {
2702 if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
2703 return;
2704 }
2705 if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2706 self.set_full_damage_pending(true);
2707 self.set_full_damage_overflow(true);
2708 self.get_mut_extra_logical_damage().clear();
2709 } else {
2710 self.get_mut_extra_logical_damage().push(rect);
2711 }
2712 }
2713 None => {
2714 self.set_full_damage_pending(true);
2715 }
2716 }
2717 }
2718
2719 fn record_subtree_logical_damage(&mut self, root: NodeId) {
2726 if self.get_full_damage_pending() {
2727 return;
2728 }
2729 let mut stack: Vec<NodeId> = vec![root];
2730 let mut visited: usize = 0;
2731 while let Some(current) = stack.pop() {
2732 let Some(raw_bounds) = self
2733 .get_node(current)
2734 .map(|node: &SceneNode| node.layout_box_ref().get_bounds())
2735 else {
2736 continue;
2737 };
2738 visited += 1;
2739 if visited > DIRTY_PAINT_FULL_THRESHOLD {
2740 self.set_full_damage_pending(true);
2741 self.set_full_damage_overflow(true);
2742 self.get_mut_extra_logical_damage().clear();
2743 return;
2744 }
2745 for child in self.children_iter(current) {
2746 stack.push(child);
2747 }
2748 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
2749 self.record_node_logical_damage(current);
2750 if self.get_full_damage_pending() {
2751 return;
2752 }
2753 }
2754 }
2755 }
2756
2757 pub fn start_transition(&mut self, mut transition: NodeTransition) {
2764 let target: NodeId = transition.get_node();
2765 let had_active: bool = self
2766 .get_transitions()
2767 .iter()
2768 .any(|transform_val: &NodeTransition| transform_val.get_node() == target);
2769 self.get_mut_transitions()
2770 .retain(|object_transform: &NodeTransition| object_transform.get_node() != target);
2771 if had_active && let Some(node) = self.get_node(target) {
2772 let paint: PaintStyle = node.get_style().get_paint();
2773 let transform_val_primary: Transform2D = paint.get_transform();
2774 let cur_op: f32 = paint.get_opacity();
2775 let cur_tx: f32 = transform_val_primary.get_translate_x();
2776 let cur_ty: f32 = transform_val_primary.get_translate_y();
2777 let cur_sc: f32 = transform_val_primary.get_scale_x();
2778 let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
2779 .hypot(transition.get_to_ty() - transition.get_from_ty())
2780 .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
2781 let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
2782 .hypot(transition.get_to_ty() - cur_ty)
2783 .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
2784 if full_dist > 0.01 {
2785 let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
2786 transition.set_duration((transition.get_duration() * ratio).max(0.05));
2787 }
2788 transition.set_from_opacity(cur_op);
2789 transition.set_from_tx(cur_tx);
2790 transition.set_from_ty(cur_ty);
2791 transition.set_from_scale(cur_sc);
2792 }
2793 self.record_node_logical_damage(target);
2794 let (opacity, transform): (f32, Transform2D) = transition.sample();
2795 let mut unhidden: bool = false;
2796 if let Some(node) = self.get_node_mut(target) {
2797 let style: &mut Style = node.get_mut_style();
2798 if !transition.get_hide_on_complete()
2799 && style.layout_ref().get_display() == Display::None
2800 {
2801 style.get_mut_layout().set_display(Display::Flex);
2802 unhidden = true;
2803 }
2804 style.get_mut_paint().set_opacity(opacity);
2805 style.get_mut_paint().set_transform(transform);
2806 }
2807 if unhidden {
2808 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2809 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2810 } else {
2811 self.mark_dirty(target, DIRTY_COMPOSITE);
2812 }
2813 self.get_mut_transitions().push(transition);
2814 }
2815
2816 pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
2827 let len: usize = self.get_transitions().len();
2828 if len == 0 {
2829 return false;
2830 }
2831 let step: f32 = dt_secs.clamp(0.001, 0.05);
2832 let mut any_updated: bool = false;
2833 let mut write_idx: usize = 0;
2834 for read_idx in 0..len {
2835 let target: NodeId = self.get_transitions()[read_idx].get_node();
2836 if self.get_node(target).is_none() {
2837 continue;
2838 }
2839 let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
2840 let transform_val: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
2841 let total_span: f32 = transform_val.get_delay() + transform_val.get_duration();
2842 let prev_elapsed: f32 = transform_val.get_elapsed();
2843 let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
2844 transform_val.set_elapsed(next_elapsed);
2845 let is_done: bool = transform_val.is_complete();
2846 let in_hold: bool =
2847 prev_elapsed > 0.0 && next_elapsed <= transform_val.get_delay() && !is_done;
2848 if in_hold {
2849 (is_done, None, false)
2850 } else {
2851 let sampled: (f32, Transform2D) = transform_val.sample();
2852 let should_hide: bool = is_done && transform_val.get_hide_on_complete();
2853 (is_done, Some(sampled), should_hide)
2854 }
2855 };
2856 if let Some((opacity, transform)) = sample_opt {
2857 self.record_node_logical_damage(target);
2858 let mut is_portal_hide: bool = false;
2859 if let Some(node) = self.get_node_mut(target) {
2860 is_portal_hide = hide && matches!(node.get_kind(), NodeKind::Portal);
2861 let style: &mut Style = node.get_mut_style();
2862 style.get_mut_paint().set_opacity(opacity);
2863 style.get_mut_paint().set_transform(transform);
2864 if hide {
2865 style.get_mut_layout().set_display(Display::None);
2866 }
2867 }
2868 if hide {
2869 self.clear_subtree_hover(target);
2870 if self
2871 .active_webview_node()
2872 .is_some_and(|webview_id: NodeId| self.is_in_subtree(webview_id, target))
2873 {
2874 self.set_active_webview_node(None);
2875 let _: bool = close_webview_sheet_bridge();
2876 }
2877 let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2878 self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2879 if is_portal_hide {
2880 self.set_full_damage_pending(true);
2881 self.clear_dirty_paint_queue();
2882 }
2883 } else {
2884 self.mark_dirty(target, DIRTY_COMPOSITE);
2885 }
2886 any_updated = true;
2887 }
2888 if !done {
2889 if write_idx != read_idx {
2890 self.get_mut_transitions().swap(write_idx, read_idx);
2891 }
2892 write_idx += 1;
2893 }
2894 }
2895 self.get_mut_transitions().truncate(write_idx);
2896 any_updated
2897 }
2898
2899 pub fn clear_subtree_hover(&mut self, root: NodeId) {
2906 let hovered_opt: Option<NodeId> = self.get_focus().hovered_node();
2907 if let Some(hovered_id) = hovered_opt
2908 && self.is_in_subtree(hovered_id, root)
2909 {
2910 self.get_mut_focus().set_hovered(None);
2911 let mut walk: Option<NodeId> = Some(hovered_id);
2912 while let Some(cur) = walk {
2913 let mut dirty_paint: bool = false;
2914 let next_parent: Option<NodeId> = if let Some(node) = self.get_node_mut(cur) {
2915 if node.get_interaction().get_hovered() {
2916 node.get_mut_interaction().set_hovered(false);
2917 dirty_paint = node.hover_paint().is_some()
2918 || node.style_ref().layout_ref().get_overflow() == Overflow::Scroll;
2919 }
2920 node.parent_id()
2921 } else {
2922 None
2923 };
2924 if dirty_paint {
2925 self.mark_dirty(cur, DIRTY_PAINT);
2926 }
2927 walk = next_parent;
2928 }
2929 }
2930 let pressed_opt: Option<NodeId> = self.get_focus().pressed_node();
2931 if let Some(pressed_id) = pressed_opt
2932 && self.is_in_subtree(pressed_id, root)
2933 {
2934 self.get_mut_focus().set_pressed(None);
2935 if let Some(node) = self.get_node_mut(pressed_id) {
2936 node.get_mut_interaction().set_pressed(false);
2937 }
2938 }
2939 let focused_opt: Option<NodeId> = self.get_focus().focused_node();
2940 if let Some(focused_id) = focused_opt
2941 && self.is_in_subtree(focused_id, root)
2942 {
2943 self.get_mut_focus().set_focused(None);
2944 if let Some(node) = self.get_node_mut(focused_id) {
2945 node.get_mut_interaction().set_focused(false);
2946 }
2947 }
2948 }
2949
2950 #[must_use]
2960 pub fn has_active_transitions(&self) -> bool {
2961 !self.get_transitions().is_empty()
2962 }
2963
2964 pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
2972 let attached: bool = if let Some(node) = self.get_node_mut(id) {
2973 node.add_lifecycle(hook);
2974 true
2975 } else {
2976 false
2977 };
2978 if attached {
2979 if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2980 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_LIFECYCLE;
2981 let next_flags: u16 = meta.get_flags() | add_flags;
2982 let _: &mut NodeMeta = meta.set_flags(next_flags);
2983 }
2984 let next_lc: usize = self.get_live_lifecycle_count().saturating_add(1);
2985 self.set_live_lifecycle_count(next_lc);
2986 }
2987 }
2988
2989 #[must_use]
3000 pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
3001 if self.get_live_lifecycle_count() == 0 {
3002 return Vec::new();
3003 }
3004 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3005 let mut stack: Vec<NodeId> = vec![root];
3006 while let Some(current) = stack.pop() {
3007 let idx: usize = current.as_usize();
3008 let Some(meta) = self.get_meta().get(idx) else {
3009 continue;
3010 };
3011 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
3012 || meta.get_generation() != current.get_generation()
3013 {
3014 continue;
3015 }
3016 if (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0 {
3017 for hook in self.get_nodes()[idx].lifecycle_observers().into_iter() {
3018 out.push((current, hook));
3019 }
3020 }
3021 for child in self.children_iter(current).rev() {
3022 stack.push(child);
3023 }
3024 }
3025 out
3026 }
3027
3028 #[must_use]
3038 pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
3039 if self.get_live_lifecycle_count() == 0 {
3040 return Vec::new();
3041 }
3042 let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3043 let mut stack: Vec<NodeId> = vec![self.get_root()];
3044 while let Some(current) = stack.pop() {
3045 if let Some(node) = self.get_node(current) {
3046 if node.layout_ref().get_display() == Display::None {
3047 continue;
3048 }
3049 if (self.get_meta()[current.as_usize()].get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
3050 {
3051 for hook in node.lifecycle_observers().into_iter() {
3052 out.push((current, hook));
3053 }
3054 }
3055 for child in self.children_iter(current).rev() {
3056 stack.push(child);
3057 }
3058 }
3059 }
3060 out
3061 }
3062
3063 #[must_use]
3074 pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
3075 let mut out: Vec<ScopeId> = Vec::new();
3076 let mut stack: Vec<NodeId> = vec![root];
3077 while let Some(current) = stack.pop() {
3078 let idx: usize = current.as_usize();
3079 let Some(meta) = self.get_meta().get(idx) else {
3080 continue;
3081 };
3082 if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
3083 || meta.get_generation() != current.get_generation()
3084 {
3085 continue;
3086 }
3087 if (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
3088 && let Some(scope) = self.get_nodes()[idx].owned_scope()
3089 {
3090 out.push(scope.id());
3091 }
3092 for child in self.children_iter(current).rev() {
3093 stack.push(child);
3094 }
3095 }
3096 out
3097 }
3098
3099 pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
3106 if self.get_transitions().is_empty() {
3107 return;
3108 }
3109 let mut ids: HashSet<NodeId> = HashSet::new();
3110 let mut stack: Vec<NodeId> = vec![root];
3111 while let Some(current) = stack.pop() {
3112 if ids.insert(current) && self.get_node(current).is_some() {
3113 for child in self.children_iter(current) {
3114 stack.push(child);
3115 }
3116 }
3117 }
3118 self.get_mut_transitions()
3119 .retain(|transform_val: &NodeTransition| !ids.contains(&transform_val.get_node()));
3120 }
3121
3122 pub fn cancel_node_transitions(&mut self, node_id: NodeId) {
3129 if self.get_transitions().is_empty() {
3130 return;
3131 }
3132 self.get_mut_transitions()
3133 .retain(|transform_val: &NodeTransition| transform_val.get_node() != node_id);
3134 }
3135
3136 pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
3144 let attached: bool = if let Some(node) = self.get_node_mut(id) {
3145 if let Some(existing) = node.owned_scope() {
3146 existing.enter(|| {
3147 on_cleanup(move || {
3148 scope.dispose();
3149 });
3150 });
3151 } else {
3152 node.set_scope(Some(scope));
3153 }
3154 true
3155 } else {
3156 false
3157 };
3158 if attached && let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
3159 let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_SCOPE;
3160 let next_flags: u16 = meta.get_flags() | add_flags;
3161 let _: &mut NodeMeta = meta.set_flags(next_flags);
3162 }
3163 }
3164
3165 #[must_use]
3176 #[inline(always)]
3177 pub(crate) fn node_paint_epoch(&self, id: NodeId) -> u32 {
3178 self.get_paint_epochs()
3179 .get(id.as_usize())
3180 .copied()
3181 .unwrap_or(0)
3182 }
3183
3184 #[cfg_attr(not(target_arch = "wasm32"), inline)]
3191 pub(crate) fn bump_node_mutation_epoch(&mut self, arena_index: usize) {
3192 if let Some(epoch) = self.get_mut_node_mutation_epochs().get_mut(arena_index) {
3193 *epoch = epoch.wrapping_add(1);
3194 }
3195 }
3196
3197 #[cfg_attr(not(target_arch = "wasm32"), inline)]
3203 pub(crate) fn bump_serial_layout_epoch(&mut self) {
3204 let next_epoch: u64 = self.get_serial_layout_epoch().wrapping_add(1);
3205 self.set_serial_layout_epoch(next_epoch);
3206 }
3207
3208 #[must_use]
3218 #[inline(always)]
3219 pub(crate) fn root_has_layout_dirty(&self) -> bool {
3220 let root_id: NodeId = self.get_root();
3221 self.get_node(root_id).is_some_and(|root_node: &SceneNode| {
3222 root_node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
3223 })
3224 }
3225
3226 fn clear_dirty_paint_queue(&mut self) {
3232 let Self {
3233 dirty_paint_nodes,
3234 meta,
3235 ..
3236 } = self;
3237 for nid in dirty_paint_nodes.drain(..) {
3238 if let Some(slot_meta) = meta.get_mut(nid.as_usize()) {
3239 let next_flags: u16 = slot_meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3240 let _: &mut NodeMeta = slot_meta.set_flags(next_flags);
3241 }
3242 }
3243 }
3244
3245 pub fn mark_dirty(&mut self, id: NodeId, mut mask: u16) {
3253 let node_idx: usize = id.as_usize();
3254 if let Some(cur_sigs) = self
3255 .get_node(id)
3256 .map(|node: &SceneNode| compute_style_sigs(node.style_ref()))
3257 && let Some(slot_sigs) = self.get_mut_style_sigs().get_mut(node_idx)
3258 {
3259 let prev_sigs: (u64, u64) = *slot_sigs;
3260 if cur_sigs != prev_sigs {
3261 *slot_sigs = cur_sigs;
3262 if cur_sigs.0 != prev_sigs.0 {
3263 mask |= DIRTY_LAYOUT | DIRTY_PAINT;
3264 }
3265 if cur_sigs.1 != prev_sigs.1 {
3266 mask |= DIRTY_TEXT | DIRTY_LAYOUT;
3267 mask |= DIRTY_PAINT;
3268 }
3269 }
3270 }
3271 let check_layout_registries: bool = (mask & DIRTY_LAYOUT) != 0;
3272 let (mut parent_opt, portal_state, scroll_state, nonzero_z_state): (
3273 Option<NodeId>,
3274 Option<bool>,
3275 Option<bool>,
3276 Option<bool>,
3277 ) = match self.get_node_mut(id) {
3278 Some(node) => {
3279 node.get_mut_dirty().insert(mask);
3280 let (portal_opt, scroll_opt, nz_z_opt): (Option<bool>, Option<bool>, Option<bool>) =
3281 if check_layout_registries {
3282 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
3283 || node.layout_ref().get_position() == Position::Fixed;
3284 let is_scroll: bool = matches!(node.get_kind(), NodeKind::ScrollView)
3285 || node.layout_ref().get_overflow() == Overflow::Scroll;
3286 let has_nz_z: bool = node.layout_ref().get_z_index() != 0;
3287 (Some(is_portal), Some(is_scroll), Some(has_nz_z))
3288 } else {
3289 (None, None, None)
3290 };
3291 (node.parent_id(), portal_opt, scroll_opt, nz_z_opt)
3292 }
3293 None => return,
3294 };
3295 if (mask & (DIRTY_PAINT | DIRTY_FULL_DAMAGE_MASK)) != 0
3296 && let Some(epoch) = self.get_mut_paint_epochs().get_mut(node_idx)
3297 {
3298 *epoch = epoch.wrapping_add(1);
3299 }
3300 if mask != DIRTY_NONE {
3301 self.bump_node_mutation_epoch(node_idx);
3302 }
3303 let prev_meta_flags: u16 = if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3304 let next_dirty: u16 = meta.get_dirty() | mask;
3305 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3306 meta.get_flags()
3307 } else {
3308 0
3309 };
3310 if let Some(is_portal) = portal_state {
3311 let was_portal: bool = (prev_meta_flags & NODE_FLAG_IS_PORTAL) != 0;
3312 if is_portal != was_portal {
3313 self.sync_portal_registration(id, is_portal);
3314 }
3315 }
3316 if let Some(is_scroll) = scroll_state {
3317 let was_scroll: bool = (prev_meta_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0;
3318 if is_scroll != was_scroll {
3319 self.sync_scroll_registration(id, is_scroll);
3320 }
3321 }
3322 if let Some(has_nz_z) = nonzero_z_state
3323 && let Some(parent_id) = parent_opt
3324 {
3325 let parent_idx: usize = parent_id.as_usize();
3326 if has_nz_z {
3327 if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
3328 let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
3329 let _: &mut NodeMeta = meta.set_flags(next_flags);
3330 }
3331 } else if self.has_nonzero_z_child(parent_id) {
3332 self.recompute_nonzero_z_child(parent_idx);
3333 }
3334 }
3335 if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
3336 self.set_layout_damage_pending(true);
3337 self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
3338 }
3339 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3340 if !self.get_full_damage_pending()
3341 && (mask & visual_mask) != 0
3342 && (prev_meta_flags & NODE_FLAG_IN_DIRTY_PAINT_QUEUE) == 0
3343 {
3344 if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
3345 self.set_full_damage_pending(true);
3346 self.set_full_damage_overflow(true);
3347 self.clear_dirty_paint_queue();
3348 } else {
3349 self.get_mut_dirty_paint_nodes().push(id);
3350 if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
3351 let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3352 let _: &mut NodeMeta = meta.set_flags(next_flags);
3353 }
3354 }
3355 }
3356 let mut ancestor_mask: u16 = DIRTY_NONE;
3357 if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
3358 ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
3359 }
3360 if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
3361 ancestor_mask |= DIRTY_SUBTREE_PAINT;
3362 }
3363 if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
3364 ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
3365 }
3366 if ancestor_mask != DIRTY_NONE {
3367 let root_has_mask: bool = {
3368 let root_id: NodeId = self.get_root();
3369 self.get_node(root_id)
3370 .map(|root_node: &SceneNode| {
3371 (root_node.get_dirty().get_bits() & ancestor_mask) == ancestor_mask
3372 })
3373 .unwrap_or(true)
3374 };
3375 let can_early_break: bool = root_has_mask && !self.get_has_stale_hidden_dirty();
3376 while let Some(ancestor_id) = parent_opt {
3377 let ancestor_idx: usize = ancestor_id.as_usize();
3378 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3379 let already: bool =
3380 (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
3381 ancestor.get_mut_dirty().insert(ancestor_mask);
3382 parent_opt = ancestor.parent_id();
3383 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3384 let next_dirty: u16 = meta.get_dirty() | ancestor_mask;
3385 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3386 }
3387 if already && can_early_break {
3388 break;
3389 }
3390 } else {
3391 break;
3392 }
3393 }
3394 }
3395 let next_rev: u64 = self.get_revision().wrapping_add(1);
3396 self.set_revision(next_rev);
3397 notify_frame_needed();
3398 }
3399
3400 #[must_use]
3411 pub fn is_node_visible(&self, id: NodeId) -> bool {
3412 let root: NodeId = self.get_root();
3413 let mut cursor: Option<NodeId> = Some(id);
3414 while let Some(cur) = cursor {
3415 let Some(node) = self.get_node(cur) else {
3416 return false;
3417 };
3418 let style: &Style = node.style_ref();
3419 if style.get_layout().get_display() == Display::None
3420 || style.get_paint().get_opacity() <= 0.001
3421 {
3422 return false;
3423 }
3424 if cur == root {
3425 return true;
3426 }
3427 cursor = node.parent_id();
3428 }
3429 false
3430 }
3431
3432 #[must_use]
3443 pub fn is_node_interactive(&self, id: NodeId) -> bool {
3444 let root: NodeId = self.get_root();
3445 let mut cursor: Option<NodeId> = Some(id);
3446 while let Some(cur) = cursor {
3447 let Some(node) = self.get_node(cur) else {
3448 return false;
3449 };
3450 let style: &Style = node.style_ref();
3451 if style.get_layout().get_display() == Display::None
3452 || style.get_paint().get_opacity() <= 0.001
3453 || style.get_paint().get_pointer_events() == PointerEvents::None
3454 {
3455 return false;
3456 }
3457 if cur == root {
3458 return true;
3459 }
3460 cursor = node.parent_id();
3461 }
3462 false
3463 }
3464
3465 pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
3476 let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
3477 damage
3478 }
3479
3480 pub(crate) fn collect_surgical_paint_damage(
3492 &mut self,
3493 scale: f32,
3494 allow_partial_layout: bool,
3495 ) -> (DamageRegion, bool) {
3496 let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
3497 let layout_pending: bool = self.get_layout_damage_pending();
3498 let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
3499 let no_extra: bool = self.get_extra_logical_damage().is_empty();
3500 if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
3501 self.set_created_since_damage(0);
3502 self.set_last_collect_composite_only(false);
3503 return (DamageRegion::default(), false);
3504 }
3505 let mut full: bool =
3506 self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
3507 let mut saw_paint_or_layout: bool = layout_pending;
3508 let mut saw_composite_or_scroll: bool = false;
3509 let mut region: DamageRegion = DamageRegion::default();
3510 if !full {
3511 let extra_len: usize = self.get_extra_logical_damage().len();
3512 for item_index in 0..extra_len {
3513 let logical_rect: Rect = self.get_extra_logical_damage()[item_index];
3514 if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
3515 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3516 }
3517 }
3518 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3519 let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3520 for outer_index in 0..dirty_len {
3521 let nid: NodeId = self.get_dirty_paint_nodes()[outer_index];
3522 let Some(node) = self.get_node(nid) else {
3523 continue;
3524 };
3525 let bits: u16 = node.get_dirty().get_bits();
3526 let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
3527 if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
3528 saw_paint_or_layout = true;
3529 }
3530 if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
3531 saw_composite_or_scroll = true;
3532 }
3533 if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
3534 full = true;
3535 break;
3536 }
3537 if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
3538 full = true;
3539 break;
3540 }
3541 if (bits & visual_mask) == 0 {
3542 continue;
3543 }
3544 let raw_bounds: Rect = node.get_layout_box().get_bounds();
3545 if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
3546 match self.node_conservative_logical_rect(nid) {
3547 Some(logical_rect) => {
3548 region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3549 }
3550 None => {
3551 full = true;
3552 break;
3553 }
3554 }
3555 } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
3556 && !has_layout_bits
3557 && node.style_ref().layout_ref().get_display() != Display::None
3558 {
3559 full = true;
3560 break;
3561 }
3562 }
3563 }
3564 self.set_last_collect_composite_only(
3565 !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
3566 );
3567 self.set_layout_damage_pending(false);
3568 self.set_created_since_damage(0);
3569 self.get_mut_extra_logical_damage().clear();
3570 if !full {
3571 let dirty_len: usize = self.get_dirty_paint_nodes().len();
3572 let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
3573 for step_index in 0..dirty_len {
3574 let nid: NodeId = self.get_dirty_paint_nodes()[step_index];
3575 let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
3576 Some(node) => {
3577 node.get_mut_dirty().remove(clear_mask);
3578 node.parent_id()
3579 }
3580 None => None,
3581 };
3582 if let Some(meta) = self.get_mut_meta().get_mut(nid.get_index() as usize) {
3583 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3584 let next_flags: u16 = meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3585 let _: &mut NodeMeta = meta.set_dirty(next_dirty).set_flags(next_flags);
3586 }
3587 while let Some(ancestor_id) = parent_opt {
3588 let ancestor_idx: usize = ancestor_id.get_index() as usize;
3589 if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3590 if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
3591 break;
3592 }
3593 ancestor.get_mut_dirty().remove(ancestor_clear);
3594 parent_opt = ancestor.parent_id();
3595 } else {
3596 break;
3597 }
3598 if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3599 let next_dirty: u16 = meta.get_dirty() & !ancestor_clear;
3600 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3601 }
3602 }
3603 }
3604 self.get_mut_dirty_paint_nodes().clear();
3605 return (region, layout_pending);
3606 }
3607 self.set_full_damage_pending(false);
3608 self.clear_dirty_paint_queue();
3609 let node_count: usize = self.get_nodes().len();
3610 for idx in 0..node_count {
3611 let should_clear: bool = {
3612 let node: &SceneNode = &self.get_nodes()[idx];
3613 node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0
3614 };
3615 if should_clear {
3616 self.get_mut_nodes()[idx].get_mut_dirty().remove(clear_mask);
3617 if let Some(meta) = self.get_mut_meta().get_mut(idx) {
3618 let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3619 let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3620 }
3621 }
3622 }
3623 (DamageRegion::full(), layout_pending)
3624 }
3625
3626 pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
3636 let was_overflow: bool = self.get_full_damage_overflow();
3637 self.set_full_damage_overflow(false);
3638 was_overflow
3639 }
3640
3641 pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
3652 if id == self.get_root() || self.get_node(id).is_none() {
3653 return (Vec::new(), Vec::new());
3654 }
3655 self.record_subtree_logical_damage(id);
3656 self.cancel_subtree_transitions(id);
3657 self.clear_subtree_hover(id);
3658 let root_parent: u32 = self.get_topology()[id.as_usize()].get_parent();
3659 if root_parent != NODE_INDEX_NONE {
3660 self.unlink_child_at(root_parent as usize, id.as_usize());
3661 }
3662 let mut stack: Vec<NodeId> = vec![id];
3663 let mut scopes: Vec<Scope> = Vec::new();
3664 let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3665 while let Some(current) = stack.pop() {
3666 let cur_idx: usize = current.as_usize();
3667 let mut next_child: u32 = self.get_topology()[cur_idx].get_first_child();
3668 let mut removed_lifecycles: usize = 0;
3669 let (was_alive, prev_flags): (bool, u16) = match self.get_node_mut(current) {
3670 Some(node) => {
3671 node.set_alive(false);
3672 node.set_kind(NodeKind::View);
3673 if node.has_extras() {
3674 if let Some(scope) = node.owned_scope() {
3675 scopes.push(scope);
3676 }
3677 let drained: Vec<Rc<dyn Lifecycle>> = node.take_lifecycles();
3678 removed_lifecycles = drained.len();
3679 for hook in drained.into_iter() {
3680 observers.push((current, hook));
3681 }
3682 node.clear_extras();
3683 }
3684 node.set_parent(None);
3685 let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
3686 node.set_generation(next_gen);
3687 (true, self.get_meta()[cur_idx].get_flags())
3688 }
3689 None => (false, 0),
3690 };
3691 if !was_alive {
3692 continue;
3693 }
3694 while next_child != NODE_INDEX_NONE {
3695 let ci: usize = next_child as usize;
3696 let sibling: u32 = self.get_topology()[ci].get_next_sibling();
3697 let child_gen: u32 = self.get_meta()[ci].get_generation();
3698 stack.push(NodeId::new(next_child, child_gen));
3699 next_child = sibling;
3700 }
3701 let next_gen: u32 = self.get_nodes()[cur_idx].get_generation();
3702 self.get_mut_meta()[cur_idx] = NodeMeta::new(next_gen, 0, DIRTY_NONE);
3703 self.get_mut_topology()[cur_idx] = NodeTopology::default();
3704 let prev_effect_id: u32 = self.get_compact_paints()[cur_idx].get_effect_id();
3705 if prev_effect_id != EFFECT_ID_NONE {
3706 self.get_mut_effect_table().remove(prev_effect_id);
3707 let _: &mut CompactPaintStyle =
3708 self.get_mut_compact_paints()[cur_idx].set_effect_id(EFFECT_ID_NONE);
3709 }
3710 let next_live: usize = self.get_live_count().saturating_sub(1);
3711 self.set_live_count(next_live);
3712 if removed_lifecycles > 0 {
3713 let next_lc: usize = self
3714 .get_live_lifecycle_count()
3715 .saturating_sub(removed_lifecycles);
3716 self.set_live_lifecycle_count(next_lc);
3717 }
3718 if (prev_flags & NODE_FLAG_IS_PORTAL) != 0 && !self.portal_nodes().is_empty() {
3719 self.sync_portal_registration(current, false);
3720 }
3721 if (prev_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0 && !self.scroll_nodes().is_empty()
3722 {
3723 self.sync_scroll_registration(current, false);
3724 }
3725 if !self.get_backdrop_blur_nodes().is_empty() {
3726 self.get_mut_backdrop_blur_nodes()
3727 .retain(|entry: &(NodeId, f32)| entry.0 != current);
3728 }
3729 if self.active_webview_node() == Some(current) {
3730 self.set_active_webview_node(None);
3731 let _: bool = close_webview_sheet_bridge();
3732 }
3733 if self.get_focus().focused_node() == Some(current) {
3734 self.get_mut_focus().set_focused(None);
3735 }
3736 if self.get_focus().hovered_node() == Some(current) {
3737 self.get_mut_focus().set_hovered(None);
3738 }
3739 if self.get_focus().pressed_node() == Some(current) {
3740 self.get_mut_focus().set_pressed(None);
3741 }
3742 let sel_hits_current: bool =
3743 self.text_selection().is_some_and(|sel: SelectionState| {
3744 sel.get_anchor_node() == current || sel.get_focus_node() == current
3745 }) || self
3746 .text_selection_spans_ref()
3747 .iter()
3748 .any(|&(nid, _, _): &(NodeId, usize, usize)| nid == current);
3749 if sel_hits_current {
3750 self.set_text_selection(None);
3751 }
3752 self.get_mut_free_list().push(current.get_index());
3753 }
3754 (scopes, observers)
3755 }
3756
3757 pub fn dispose_subtree(&mut self, id: NodeId) {
3764 let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
3765 finalize_disposed_subtree(scopes, observers);
3766 }
3767
3768 pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
3779 let prev: Option<NodeId> = self.get_focus().focused_node();
3780 if prev == target {
3781 return Vec::new();
3782 }
3783 let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
3784 if let Some(old_id) = prev {
3785 if let Some(old_node) = self.get_node_mut(old_id) {
3786 old_node.get_mut_interaction().set_focused(false);
3787 if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
3788 callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
3789 }
3790 }
3791 self.mark_dirty(old_id, DIRTY_PAINT);
3792 }
3793 self.get_mut_focus().set_focused(target);
3794 if let Some(new_id) = target {
3795 if let Some(new_node) = self.get_node_mut(new_id) {
3796 new_node.get_mut_interaction().set_focused(true);
3797 if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
3798 callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
3799 }
3800 }
3801 self.mark_dirty(new_id, DIRTY_PAINT);
3802 }
3803 callbacks
3804 }
3805
3806 #[must_use]
3817 pub fn effective_text_select_mode(&self, id: NodeId) -> TextSelectMode {
3818 let mut cursor: Option<NodeId> = Some(id);
3819 while let Some(cur) = cursor {
3820 let Some(node) = self.get_node(cur) else {
3821 return TextSelectMode::None;
3822 };
3823 if let Some(mode) = node.style_ref().text_ref().text_select_mode() {
3824 return mode;
3825 }
3826 cursor = node.parent_id();
3827 }
3828 TextSelectMode::None
3829 }
3830
3831 #[must_use]
3842 pub fn is_node_selectable(&self, id: NodeId) -> bool {
3843 self.effective_text_select_mode(id) != TextSelectMode::None
3844 }
3845
3846 #[must_use]
3857 pub(crate) fn selectable_scope_root(&self, id: NodeId) -> Option<(NodeId, TextSelectMode)> {
3858 let target_mode: TextSelectMode = self.effective_text_select_mode(id);
3859 if target_mode == TextSelectMode::None {
3860 return None;
3861 }
3862 let mut scope: NodeId = id;
3863 loop {
3864 let cur_node: &SceneNode = self.get_node(scope)?;
3865 if matches!(cur_node.get_kind(), NodeKind::Portal) {
3866 break;
3867 }
3868 let Some(parent_id) = cur_node.parent_id() else {
3869 break;
3870 };
3871 if self.effective_text_select_mode(parent_id) != target_mode {
3872 break;
3873 }
3874 scope = parent_id;
3875 }
3876 Some((scope, target_mode))
3877 }
3878
3879 #[must_use]
3890 pub(crate) fn selectable_scope_text_nodes(&self, id: NodeId) -> Vec<NodeId> {
3891 let Some((scope_root, target_mode)) = self.selectable_scope_root(id) else {
3892 return Vec::new();
3893 };
3894 let mut out: Vec<NodeId> = Vec::new();
3895 let mut stack: Vec<NodeId> = vec![scope_root];
3896 while let Some(cid) = stack.pop() {
3897 let Some(node) = self.get_node(cid) else {
3898 continue;
3899 };
3900 if !node.get_alive() || node.style_ref().get_layout().get_display() == Display::None {
3901 continue;
3902 }
3903 if cid != scope_root {
3904 if matches!(node.get_kind(), NodeKind::Portal) {
3905 continue;
3906 }
3907 if node
3908 .style_ref()
3909 .text_ref()
3910 .text_select_mode()
3911 .is_some_and(|matrix_elems: TextSelectMode| matrix_elems != target_mode)
3912 {
3913 continue;
3914 }
3915 }
3916 if matches!(node.get_kind(), NodeKind::Text(_)) {
3917 out.push(cid);
3918 } else {
3919 let start_len: usize = stack.len();
3920 stack.extend(self.children_iter(cid));
3921 stack[start_len..].reverse();
3922 }
3923 }
3924 out
3925 }
3926
3927 #[must_use]
3938 pub(crate) fn text_node_screen_content_rect(&self, node_id: NodeId) -> Option<Rect> {
3939 let node: &SceneNode = self.get_node(node_id)?;
3940 let computed_box: LayoutBox = node.get_layout_box();
3941 let outer: Rect = computed_box.get_bounds();
3942 let content_rect: Rect = computed_box.get_content_bounds();
3943 let screen_outer: Rect = self.node_screen_bounds(node_id).unwrap_or(outer);
3944 Some(Rect::new(
3945 screen_outer.get_x() + (content_rect.get_x() - outer.get_x()),
3946 screen_outer.get_y() + (content_rect.get_y() - outer.get_y()),
3947 content_rect.get_width(),
3948 content_rect.get_height(),
3949 ))
3950 }
3951
3952 #[must_use]
3964 fn is_new_visual_row(&self, prev_id: NodeId, cur_id: NodeId) -> bool {
3965 let prev_rect: Option<Rect> = self.text_node_screen_content_rect(prev_id);
3966 let cur_rect: Option<Rect> = self.text_node_screen_content_rect(cur_id);
3967 if let (Some(pr), Some(cr)) = (prev_rect, cur_rect)
3968 && pr.get_height() > 0.0
3969 && cr.get_height() > 0.0
3970 {
3971 let prev_cy: f32 = pr.get_y() + pr.get_height() * 0.5;
3972 let cur_cy: f32 = cr.get_y() + cr.get_height() * 0.5;
3973 let threshold: f32 = (pr.get_height().min(cr.get_height()) * 0.5).max(4.0);
3974 return (cur_cy - prev_cy).abs() > threshold;
3975 }
3976 let prev_parent: Option<NodeId> = self.get_node(prev_id).and_then(SceneNode::parent_id);
3977 let cur_parent: Option<NodeId> = self.get_node(cur_id).and_then(SceneNode::parent_id);
3978 if let (Some(pp), Some(cp)) = (prev_parent, cur_parent)
3979 && pp == cp
3980 && let Some(pnode) = self.get_node(pp)
3981 && pnode.style_ref().get_layout().get_flex_direction() == FlexDirection::Row
3982 {
3983 return false;
3984 }
3985 true
3986 }
3987
3988 #[must_use]
3999 fn resolve_selection_spans(&self, selection: SelectionState) -> Vec<(NodeId, usize, usize)> {
4000 if selection.is_empty() {
4001 return Vec::new();
4002 }
4003 if selection.is_single_node() {
4004 let nid: NodeId = selection.get_anchor_node();
4005 let Some(node) = self.get_node(nid) else {
4006 return Vec::new();
4007 };
4008 let NodeKind::Text(content) = node.get_kind() else {
4009 return Vec::new();
4010 };
4011 let len: usize = content.chars().count();
4012 let (raw_s, raw_e): (usize, usize) = selection.ordered_range();
4013 let start_c: usize = raw_s.min(len);
4014 let end_c: usize = raw_e.min(len);
4015 return if start_c < end_c {
4016 vec![(nid, start_c, end_c)]
4017 } else {
4018 Vec::new()
4019 };
4020 }
4021 let anchor_id: NodeId = selection.get_anchor_node();
4022 let focus_id: NodeId = selection.get_focus_node();
4023 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_id);
4024 let anchor_pos: Option<usize> = nodes
4025 .iter()
4026 .position(|target_node_id: &NodeId| *target_node_id == anchor_id);
4027 let focus_pos: Option<usize> = nodes
4028 .iter()
4029 .position(|element_id: &NodeId| *element_id == focus_id);
4030 let (Some(a_pos), Some(f_pos)) = (anchor_pos, focus_pos) else {
4031 return Vec::new();
4032 };
4033 let (start_pos, start_ch, end_pos, end_ch): (usize, usize, usize, usize) = if a_pos <= f_pos
4034 {
4035 (
4036 a_pos,
4037 selection.get_anchor_char(),
4038 f_pos,
4039 selection.get_focus_char(),
4040 )
4041 } else {
4042 (
4043 f_pos,
4044 selection.get_focus_char(),
4045 a_pos,
4046 selection.get_anchor_char(),
4047 )
4048 };
4049 let mut spans: Vec<(NodeId, usize, usize)> =
4050 Vec::with_capacity(end_pos.saturating_sub(start_pos) + 1);
4051 for (idx, &nid) in nodes.iter().enumerate().take(end_pos + 1).skip(start_pos) {
4052 let Some(node) = self.get_node(nid) else {
4053 continue;
4054 };
4055 let NodeKind::Text(content) = node.get_kind() else {
4056 continue;
4057 };
4058 let len: usize = content.chars().count();
4059 let source_val: usize = if idx == start_pos {
4060 start_ch.min(len)
4061 } else {
4062 0
4063 };
4064 let event_ref: usize = if idx == end_pos { end_ch.min(len) } else { len };
4065 if source_val < event_ref || (idx > start_pos && idx < end_pos) {
4066 spans.push((nid, source_val, event_ref));
4067 }
4068 }
4069 spans
4070 }
4071
4072 #[must_use]
4082 pub(crate) fn text_selection_spans_ref(&self) -> &[(NodeId, usize, usize)] {
4083 let Self {
4084 text_selection_spans,
4085 ..
4086 } = self;
4087 text_selection_spans.as_slice()
4088 }
4089
4090 #[must_use]
4101 pub(crate) fn text_selection_range_for(&self, id: NodeId) -> Option<(usize, usize)> {
4102 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4103 if spans.is_empty() {
4104 return None;
4105 }
4106 for &(nid, source_val, event_ref) in spans.iter() {
4107 if nid == id {
4108 return if source_val < event_ref {
4109 Some((source_val, event_ref))
4110 } else {
4111 None
4112 };
4113 }
4114 }
4115 None
4116 }
4117
4118 #[must_use]
4130 pub(crate) fn is_descendant_of(&self, id: NodeId, ancestor: NodeId) -> bool {
4131 let mut cursor: Option<NodeId> = Some(id);
4132 while let Some(cur) = cursor {
4133 if cur == ancestor {
4134 return true;
4135 }
4136 cursor = self.get_node(cur).and_then(SceneNode::parent_id);
4137 }
4138 false
4139 }
4140
4141 #[must_use]
4152 pub fn effective_selection_color(&self, id: NodeId) -> Color {
4153 let mut cursor: Option<NodeId> = Some(id);
4154 while let Some(cur) = cursor {
4155 let Some(node) = self.get_node(cur) else {
4156 break;
4157 };
4158 if let Some(color) = node.style_ref().text_ref().selection_color() {
4159 return color;
4160 }
4161 cursor = node.parent_id();
4162 }
4163 DEFAULT_TEXT_SELECTION_COLOR
4164 }
4165
4166 #[must_use]
4176 pub fn text_selection(&self) -> Option<SelectionState> {
4177 let Self { text_selection, .. } = self;
4178 *text_selection
4179 }
4180
4181 pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
4188 let prev: Option<SelectionState> = self.text_selection();
4189 if prev == selection {
4190 return;
4191 }
4192 let mut dirty_ids: Vec<NodeId> =
4193 Vec::with_capacity(self.text_selection_spans_ref().len() + 4);
4194 for &(nid, _, _) in self.text_selection_spans_ref().iter() {
4195 dirty_ids.push(nid);
4196 }
4197 if let Some(old_sel) = prev {
4198 dirty_ids.push(old_sel.get_anchor_node());
4199 if !old_sel.is_single_node() {
4200 dirty_ids.push(old_sel.get_focus_node());
4201 }
4202 }
4203 let next_spans: Vec<(NodeId, usize, usize)> = selection
4204 .map(|sel: SelectionState| self.resolve_selection_spans(sel))
4205 .unwrap_or_default();
4206 for &(nid, _, _) in next_spans.iter() {
4207 dirty_ids.push(nid);
4208 }
4209 if let Some(new_sel) = selection {
4210 dirty_ids.push(new_sel.get_anchor_node());
4211 if !new_sel.is_single_node() {
4212 dirty_ids.push(new_sel.get_focus_node());
4213 }
4214 }
4215 let Self {
4216 text_selection,
4217 text_selection_spans,
4218 ..
4219 } = self;
4220 *text_selection = selection;
4221 *text_selection_spans = next_spans;
4222 for nid in dirty_ids.into_iter() {
4223 self.mark_dirty(nid, DIRTY_PAINT);
4224 }
4225 }
4226
4227 pub fn clear_text_selection(&mut self) {
4233 self.set_text_selection(None);
4234 }
4235
4236 #[must_use]
4247 fn extract_selected_text_filtered(&self, container: Option<NodeId>) -> Option<String> {
4248 let sel: SelectionState = self.text_selection()?;
4249 if sel.is_empty() {
4250 return None;
4251 }
4252 if let Some(root) = container
4253 && !self.is_descendant_of(sel.get_anchor_node(), root)
4254 {
4255 return None;
4256 }
4257 let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
4258 if spans.is_empty() {
4259 return None;
4260 }
4261 if spans.len() == 1 {
4262 let (nid, source_val, event_ref): (NodeId, usize, usize) = spans[0];
4263 if let Some(root) = container
4264 && !self.is_descendant_of(nid, root)
4265 {
4266 return None;
4267 }
4268 let node: &SceneNode = self.get_node(nid)?;
4269 let NodeKind::Text(content) = node.get_kind() else {
4270 return None;
4271 };
4272 let extracted: &str = extract_char_range(content.as_str(), source_val, event_ref);
4273 return if extracted.is_empty() {
4274 None
4275 } else {
4276 Some(extracted.to_string())
4277 };
4278 }
4279 let mut out: String = String::new();
4280 let mut prev_emitted_node: Option<NodeId> = None;
4281 let last_span_idx: usize = spans.len().saturating_sub(1);
4282 for (idx, &(nid, scale_val, error_val)) in spans.iter().enumerate() {
4283 if let Some(root) = container
4284 && !self.is_descendant_of(nid, root)
4285 {
4286 continue;
4287 }
4288 let Some(node) = self.get_node(nid) else {
4289 continue;
4290 };
4291 let NodeKind::Text(content) = node.get_kind() else {
4292 continue;
4293 };
4294 let part: &str = extract_char_range(content.as_str(), scale_val, error_val);
4295 let is_middle_empty: bool = part.is_empty() && idx > 0 && idx < last_span_idx;
4296 if part.is_empty() && !is_middle_empty {
4297 continue;
4298 }
4299 if let Some(prev_id) = prev_emitted_node
4300 && self.is_new_visual_row(prev_id, nid)
4301 {
4302 out.push('\n');
4303 }
4304 out.push_str(part);
4305 prev_emitted_node = Some(nid);
4306 }
4307 if out.is_empty() { None } else { Some(out) }
4308 }
4309
4310 #[must_use]
4320 pub fn get_selected_text(&self) -> Option<String> {
4321 if let Some(sel) = self.extract_selected_text_filtered(None) {
4322 return Some(sel);
4323 }
4324 let focused: NodeId = self.get_focus().focused_node()?;
4325 let node: &SceneNode = self.get_node(focused)?;
4326 if let NodeKind::Input(state) = node.get_kind() {
4327 return state.selected_text().map(str::to_string);
4328 }
4329 None
4330 }
4331
4332 #[must_use]
4343 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4344 self.extract_selected_text_filtered(Some(container))
4345 }
4346
4347 pub fn select_all_text(&mut self, id: NodeId) -> bool {
4358 if !self.is_node_selectable(id) {
4359 return false;
4360 }
4361 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4362 let Some(&first_id) = nodes.first() else {
4363 return false;
4364 };
4365 let Some(&last_id) = nodes.last() else {
4366 return false;
4367 };
4368 let last_len: usize = self
4369 .get_node(last_id)
4370 .and_then(|node: &SceneNode| {
4371 if let NodeKind::Text(content) = node.get_kind() {
4372 Some(content.chars().count())
4373 } else {
4374 None
4375 }
4376 })
4377 .unwrap_or(0);
4378 if nodes.len() == 1 && last_len == 0 {
4379 return false;
4380 }
4381 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4382 true
4383 }
4384
4385 pub(crate) fn select_line_text(&mut self, id: NodeId) -> bool {
4396 if !self.is_node_selectable(id) {
4397 return false;
4398 }
4399 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4400 let Some(pos) = nodes
4401 .iter()
4402 .position(|target_node_id: &NodeId| *target_node_id == id)
4403 else {
4404 return false;
4405 };
4406 let mut start_idx: usize = pos;
4407 while start_idx > 0 && !self.is_new_visual_row(nodes[start_idx - 1], id) {
4408 start_idx -= 1;
4409 }
4410 let mut end_idx: usize = pos;
4411 while end_idx + 1 < nodes.len() && !self.is_new_visual_row(id, nodes[end_idx + 1]) {
4412 end_idx += 1;
4413 }
4414 let first_id: NodeId = nodes[start_idx];
4415 let last_id: NodeId = nodes[end_idx];
4416 let last_len: usize = self
4417 .get_node(last_id)
4418 .and_then(|node: &SceneNode| {
4419 if let NodeKind::Text(content) = node.get_kind() {
4420 Some(content.chars().count())
4421 } else {
4422 None
4423 }
4424 })
4425 .unwrap_or(0);
4426 if first_id == last_id && last_len == 0 {
4427 return false;
4428 }
4429 self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4430 true
4431 }
4432
4433 #[must_use]
4445 pub(crate) fn hit_test_selectable_scope(
4446 &self,
4447 anchor_or_hit: NodeId,
4448 pos: Point,
4449 ) -> Option<(NodeId, usize)> {
4450 let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_or_hit);
4451 if nodes.is_empty() {
4452 return None;
4453 }
4454 let mut rects: Vec<(NodeId, Rect, TextStyle, usize)> = Vec::with_capacity(nodes.len());
4455 let mut overall_min_y: f32 = f32::INFINITY;
4456 let mut overall_max_y: f32 = f32::NEG_INFINITY;
4457 for &nid in nodes.iter() {
4458 let Some(node) = self.get_node(nid) else {
4459 continue;
4460 };
4461 let NodeKind::Text(content) = node.get_kind() else {
4462 continue;
4463 };
4464 let Some(rect) = self.text_node_screen_content_rect(nid) else {
4465 continue;
4466 };
4467 let tstyle: TextStyle = node.get_style().get_text();
4468 if pos.get_x() >= rect.get_x()
4469 && pos.get_x() <= rect.right()
4470 && pos.get_y() >= rect.get_y()
4471 && pos.get_y() <= rect.bottom()
4472 {
4473 let ch: usize = hit_test_text_char(content.as_str(), tstyle, rect, pos);
4474 return Some((nid, ch));
4475 }
4476 if rect.get_y() < overall_min_y {
4477 overall_min_y = rect.get_y();
4478 }
4479 if rect.bottom() > overall_max_y {
4480 overall_max_y = rect.bottom();
4481 }
4482 rects.push((nid, rect, tstyle, content.chars().count()));
4483 }
4484 if rects.is_empty() {
4485 return None;
4486 }
4487 if pos.get_y() < overall_min_y - 4.0 {
4488 return Some((rects[0].0, 0));
4489 }
4490 if pos.get_y() > overall_max_y + 4.0 {
4491 let last: (NodeId, Rect, TextStyle, usize) = rects[rects.len() - 1];
4492 return Some((last.0, last.3));
4493 }
4494 let mut min_dy: f32 = f32::INFINITY;
4495 for &(_, rect, _, _) in rects.iter() {
4496 let dy: f32 = if pos.get_y() < rect.get_y() {
4497 rect.get_y() - pos.get_y()
4498 } else if pos.get_y() > rect.bottom() {
4499 pos.get_y() - rect.bottom()
4500 } else {
4501 0.0
4502 };
4503 if dy < min_dy {
4504 min_dy = dy;
4505 }
4506 }
4507 let mut best: Option<(NodeId, Rect, TextStyle, f32, f32)> = None;
4508 for &(nid, rect, tstyle, _) in rects.iter() {
4509 let dy: f32 = if pos.get_y() < rect.get_y() {
4510 rect.get_y() - pos.get_y()
4511 } else if pos.get_y() > rect.bottom() {
4512 pos.get_y() - rect.bottom()
4513 } else {
4514 0.0
4515 };
4516 if dy > min_dy + 2.0 {
4517 continue;
4518 }
4519 let dx: f32 = if pos.get_x() < rect.get_x() {
4520 rect.get_x() - pos.get_x()
4521 } else if pos.get_x() > rect.right() {
4522 pos.get_x() - rect.right()
4523 } else {
4524 0.0
4525 };
4526 let better: bool = match best {
4527 None => true,
4528 Some((_, _, _, b_dx, b_dy)) => dx < b_dx || (dx == b_dx && dy < b_dy),
4529 };
4530 if better {
4531 best = Some((nid, rect, tstyle, dx, dy));
4532 }
4533 }
4534 let (best_nid, best_rect, best_style, _, _): (NodeId, Rect, TextStyle, f32, f32) = best?;
4535 let best_node: &SceneNode = self.get_node(best_nid)?;
4536 let NodeKind::Text(content) = best_node.get_kind() else {
4537 return None;
4538 };
4539 let min_y: f32 = best_rect.get_y() + 0.5;
4540 let max_y: f32 = (best_rect.bottom() - 0.5).max(min_y);
4541 let clamped_y: f32 = pos.get_y().clamp(min_y, max_y);
4542 let ch: usize = hit_test_text_char(
4543 content.as_str(),
4544 best_style,
4545 best_rect,
4546 Point::new(pos.get_x(), clamped_y),
4547 );
4548 Some((best_nid, ch))
4549 }
4550}
4551
4552impl SceneBorrowGuard {
4554 #[inline(always)]
4560 pub(crate) fn enter() -> Self {
4561 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4562 depth.set(depth.get().saturating_add(1));
4563 });
4564 Self
4565 }
4566}
4567
4568impl Drop for SceneBorrowGuard {
4570 #[inline(always)]
4576 fn drop(&mut self) {
4577 let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4578 depth.set(depth.get().saturating_sub(1));
4579 });
4580 }
4581}
4582
4583impl SceneHandle {
4585 #[must_use]
4591 pub fn new_tree() -> Self {
4592 Self {
4593 inner: Rc::new(SceneHandleInner {
4594 tree: RefCell::new(SceneTree::default()),
4595 has_deferred: Cell::new(false),
4596 deferred_writes: RefCell::new(Vec::new()),
4597 }),
4598 }
4599 }
4600
4601 #[must_use]
4611 #[inline(always)]
4612 pub fn has_deferred_writes(&self) -> bool {
4613 let Self { inner } = self;
4614 inner.has_deferred.get()
4615 }
4616
4617 fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
4628 let mut executed: usize = 0;
4629 for _ in 0..MAX_FLUSH_ITERATIONS {
4630 let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
4631 Ok(mut queue) => {
4632 inner.has_deferred.set(false);
4633 if queue.is_empty() {
4634 break;
4635 }
4636 take(&mut *queue)
4637 }
4638 Err(_) => break,
4639 };
4640 for op in batch.into_iter() {
4641 op(tree);
4642 executed = executed.saturating_add(1);
4643 }
4644 if !inner.has_deferred.get() {
4645 break;
4646 }
4647 }
4648 executed
4649 }
4650
4651 pub fn flush_deferred_writes(&self) -> usize {
4661 let Self { inner } = self;
4662 if !inner.has_deferred.get() {
4663 return 0;
4664 }
4665 let executed: usize = match inner.tree.try_borrow_mut() {
4666 Ok(mut guard) => {
4667 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4668 Self::drain_deferred_locked(inner, &mut guard)
4669 }
4670 Err(_) => return 0,
4671 };
4672 if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
4673 self.flush_after_outer_borrow();
4674 }
4675 executed
4676 }
4677
4678 #[inline(always)]
4684 fn finish_outer_borrow(&self) {
4685 if is_scene_borrowed() || panicking() {
4686 return;
4687 }
4688 let Self { inner } = self;
4689 if !inner.has_deferred.get() && !has_deferred_effect_flush() {
4690 return;
4691 }
4692 self.flush_after_outer_borrow();
4693 }
4694
4695 #[cold]
4701 fn flush_after_outer_borrow(&self) {
4702 let Self { inner } = self;
4703 for _ in 0..MAX_FLUSH_ITERATIONS {
4704 let drained_writes: usize = if inner.has_deferred.get() {
4705 match inner.tree.try_borrow_mut() {
4706 Ok(mut guard) => {
4707 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4708 Self::drain_deferred_locked(inner, &mut guard)
4709 }
4710 Err(_) => 0,
4711 }
4712 } else {
4713 0
4714 };
4715 let flushed_effects: bool = if take_deferred_effect_flush() {
4716 flush_effects();
4717 true
4718 } else {
4719 false
4720 };
4721 if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
4722 break;
4723 }
4724 }
4725 }
4726
4727 pub fn mutate<CallbackFn>(&self, operation: CallbackFn)
4734 where
4735 CallbackFn: FnOnce(&mut SceneTree) + 'static,
4736 {
4737 let ran_inline: bool = {
4738 let Self { inner } = self;
4739 match inner.tree.try_borrow_mut() {
4740 Ok(mut guard) => {
4741 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4742 operation(&mut guard);
4743 if inner.has_deferred.get() {
4744 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4745 }
4746 true
4747 }
4748 Err(_) => {
4749 if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
4750 queue.push(Box::new(operation));
4751 inner.has_deferred.set(true);
4752 }
4753 notify_frame_needed();
4754 false
4755 }
4756 }
4757 };
4758 if ran_inline {
4759 self.finish_outer_borrow();
4760 }
4761 }
4762
4763 pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
4772 self.mutate(move |tree: &mut SceneTree| {
4773 tree.set_virtual_scroll(id, scroll_y, content_height);
4774 });
4775 }
4776
4777 #[must_use]
4788 pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
4789 self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
4790 }
4791
4792 pub fn start_transition(&self, transition: NodeTransition) {
4799 self.mutate(move |tree: &mut SceneTree| {
4800 tree.start_transition(transition);
4801 });
4802 }
4803
4804 pub fn mark_dirty(&self, id: NodeId, mask: u16) {
4812 self.mutate(move |tree: &mut SceneTree| {
4813 tree.mark_dirty(id, mask);
4814 });
4815 }
4816
4817 pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
4825 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4826 |tree: &mut SceneTree| {
4827 if tree.get_node(parent).is_none() {
4828 return (Vec::new(), Vec::new());
4829 }
4830 let parent_idx: usize = parent.as_usize();
4831 let old_children: Vec<NodeId> = tree.children_vec(parent);
4832 tree.unlink_all_children_at(parent_idx);
4833 let mut all_scopes: Vec<Scope> = Vec::new();
4834 let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
4835 if new_children.is_empty() {
4836 for old_child in old_children.into_iter() {
4837 let (scale_factor, ob): DisposedSubtreePayload =
4838 tree.dispose_subtree_collect(old_child);
4839 all_scopes.extend(scale_factor);
4840 all_obs.extend(ob);
4841 }
4842 } else if old_children.len() > 16 && new_children.len() > 16 {
4843 let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
4844 for old_child in old_children.into_iter() {
4845 if !keep_set.contains(&old_child) {
4846 let (dpi_scale, ob): DisposedSubtreePayload =
4847 tree.dispose_subtree_collect(old_child);
4848 all_scopes.extend(dpi_scale);
4849 all_obs.extend(ob);
4850 }
4851 }
4852 } else {
4853 for old_child in old_children.into_iter() {
4854 if !new_children.contains(&old_child) {
4855 let (scroll_val, ob): DisposedSubtreePayload =
4856 tree.dispose_subtree_collect(old_child);
4857 all_scopes.extend(scroll_val);
4858 all_obs.extend(ob);
4859 }
4860 }
4861 }
4862 for child in new_children.into_iter() {
4863 if child == parent || tree.get_node(child).is_none() {
4864 continue;
4865 }
4866 let child_idx: usize = child.as_usize();
4867 let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
4868 if prev_parent != NODE_INDEX_NONE {
4869 tree.unlink_child_at(prev_parent as usize, child_idx);
4870 }
4871 tree.link_child_tail_at(parent_idx, parent, child_idx);
4872 }
4873 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4874 (all_scopes, all_obs)
4875 },
4876 (Vec::new(), Vec::new()),
4877 );
4878 finalize_disposed_subtree(scopes, observers);
4879 }
4880
4881 pub fn dismiss_portal_immediate(&self, portal: NodeId) {
4888 self.replace_children_safe(portal, Vec::new());
4889 self.with_write(
4890 |tree: &mut SceneTree| {
4891 tree.cancel_subtree_transitions(portal);
4892 tree.clear_subtree_hover(portal);
4893 if let Some(node) = tree.get_node_mut(portal) {
4894 let computed_style: &mut Style = node.get_mut_style();
4895 computed_style.get_mut_layout().set_display(Display::None);
4896 computed_style
4897 .get_mut_paint()
4898 .set_pointer_events(PointerEvents::None)
4899 .set_opacity(0.0);
4900 }
4901 let dirty_l: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
4902 tree.mark_dirty(portal, dirty_l | DIRTY_PAINT);
4903 tree.set_full_damage_pending(true);
4904 tree.clear_dirty_paint_queue();
4905 },
4906 (),
4907 );
4908 notify_frame_needed();
4909 }
4910
4911 pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
4919 let (scopes, observers): DisposedSubtreePayload = self.with_write(
4920 |tree: &mut SceneTree| {
4921 if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
4922 tree.unlink_child_at(parent.as_usize(), child.as_usize());
4923 }
4924 let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
4925 tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4926 out
4927 },
4928 (Vec::new(), Vec::new()),
4929 );
4930 finalize_disposed_subtree(scopes, observers);
4931 }
4932
4933 pub fn mutate_style<CallbackFn>(&self, id: NodeId, mutator: CallbackFn) -> bool
4945 where
4946 CallbackFn: FnOnce(&mut Style),
4947 {
4948 self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
4949 }
4950
4951 pub fn freeze_subtree(&self, root: NodeId) {
4958 request_cancel_scroll_inertia();
4959 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4960 |tree: &mut SceneTree| {
4961 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4962 tree.cancel_subtree_transitions(root);
4963 let changed: bool = if let Some(node) = tree.get_node_mut(root) {
4964 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4965 if layout.get_display() == Display::None {
4966 false
4967 } else {
4968 layout.set_display(Display::None);
4969 true
4970 }
4971 } else {
4972 false
4973 };
4974 if changed {
4975 tree.clear_subtree_hover(root);
4976 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4977 }
4978 obs
4979 },
4980 Vec::new(),
4981 );
4982 dispatch_lifecycle_freeze(&observers);
4983 }
4984
4985 pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
4993 request_cancel_scroll_inertia();
4994 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4995 |tree: &mut SceneTree| {
4996 let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4997 tree.cancel_subtree_transitions(root);
4998 let mut demoted_fixed: bool = false;
4999 let mut prev_z: i32 = 0;
5000 if let Some(node) = tree.get_node_mut(root) {
5001 let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
5002 let computed_style: &mut Style = node.get_mut_style();
5003 prev_z = computed_style.layout_ref().get_z_index();
5004 demoted_fixed =
5005 !is_portal && computed_style.layout_ref().get_position() == Position::Fixed;
5006 computed_style
5007 .get_mut_layout()
5008 .set_position(Position::Absolute)
5009 .set_top(Some(0.0))
5010 .set_right(Some(0.0))
5011 .set_bottom(None)
5012 .set_left(Some(0.0))
5013 .set_z_index(0);
5014 computed_style
5015 .get_mut_paint()
5016 .set_pointer_events(PointerEvents::None);
5017 }
5018 if prev_z != 0 {
5019 let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
5020 if parent_idx != NODE_INDEX_NONE {
5021 tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
5022 }
5023 }
5024 tree.clear_subtree_hover(root);
5025 if demoted_fixed {
5026 tree.sync_portal_registration(root, false);
5027 }
5028 tree.start_transition(exit_transition.with_hide_on_complete(true));
5029 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
5030 obs
5031 },
5032 Vec::new(),
5033 );
5034 dispatch_lifecycle_freeze(&observers);
5035 }
5036
5037 pub fn resume_subtree(&self, root: NodeId) {
5044 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
5045 |tree: &mut SceneTree| {
5046 let mut unhidden: bool = false;
5047 if let Some(node) = tree.get_node_mut(root) {
5048 let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
5049 if layout.get_display() == Display::None {
5050 layout.set_display(Display::Flex);
5051 unhidden = true;
5052 }
5053 }
5054 if unhidden {
5055 tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
5056 } else {
5057 tree.mark_dirty(root, DIRTY_PAINT);
5058 }
5059 tree.collect_subtree_lifecycles(root)
5060 },
5061 Vec::new(),
5062 );
5063 dispatch_lifecycle_resume(&observers);
5064 }
5065
5066 pub fn activate_subtree(&self, root: NodeId) {
5073 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
5074 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
5075 Vec::new(),
5076 );
5077 dispatch_lifecycle_activate(&observers);
5078 }
5079
5080 pub fn update_subtree(&self, root: NodeId) {
5087 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
5088 |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
5089 Vec::new(),
5090 );
5091 dispatch_lifecycle_update(&observers);
5092 }
5093
5094 pub fn emit_subtree_appear(&self, root: NodeId) {
5101 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
5102 |tree: &SceneTree| {
5103 (
5104 tree.collect_subtree_lifecycles(root),
5105 tree.collect_subtree_scope_ids(root),
5106 )
5107 },
5108 (Vec::new(), Vec::new()),
5109 );
5110 let system_event: SystemEvent = SystemEvent::Appear;
5111 dispatch_lifecycle_system_event(&observers, &system_event);
5112 dispatch_system_event_to_scopes(&scopes, &system_event);
5113 }
5114
5115 pub fn emit_subtree_disappear(&self, root: NodeId) {
5122 let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
5123 |tree: &SceneTree| {
5124 (
5125 tree.collect_subtree_lifecycles(root),
5126 tree.collect_subtree_scope_ids(root),
5127 )
5128 },
5129 (Vec::new(), Vec::new()),
5130 );
5131 let system_event: SystemEvent = SystemEvent::Disappear;
5132 dispatch_lifecycle_system_event(&observers, &system_event);
5133 dispatch_system_event_to_scopes(&scopes, &system_event);
5134 }
5135
5136 #[must_use]
5146 pub fn has_active_transitions(&self) -> bool {
5147 self.with_read(SceneTree::has_active_transitions, false)
5148 }
5149
5150 #[must_use]
5160 pub fn get_selected_text(&self) -> Option<String> {
5161 self.with_read(SceneTree::get_selected_text, None)
5162 }
5163
5164 #[must_use]
5175 pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
5176 self.with_read(
5177 |tree: &SceneTree| tree.get_selected_text_within(container),
5178 None,
5179 )
5180 }
5181
5182 pub fn clear_text_selection(&self) {
5188 self.mutate(SceneTree::clear_text_selection);
5189 }
5190
5191 pub fn with_read<CallbackFn, ReturnValue>(
5203 &self,
5204 operation: CallbackFn,
5205 fallback: ReturnValue,
5206 ) -> ReturnValue
5207 where
5208 CallbackFn: FnOnce(&SceneTree) -> ReturnValue,
5209 {
5210 let result: ReturnValue = {
5211 let Self { inner } = self;
5212 match inner.tree.try_borrow() {
5213 Ok(guard) => {
5214 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5215 operation(&guard)
5216 }
5217 Err(_) => return fallback,
5218 }
5219 };
5220 self.finish_outer_borrow();
5221 result
5222 }
5223
5224 pub fn with_write<CallbackFn, ReturnValue>(
5236 &self,
5237 operation: CallbackFn,
5238 fallback: ReturnValue,
5239 ) -> ReturnValue
5240 where
5241 CallbackFn: FnOnce(&mut SceneTree) -> ReturnValue,
5242 {
5243 let result: ReturnValue = {
5244 let Self { inner } = self;
5245 match inner.tree.try_borrow_mut() {
5246 Ok(mut guard) => {
5247 let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
5248 let out: ReturnValue = operation(&mut guard);
5249 if inner.has_deferred.get() {
5250 let _: usize = Self::drain_deferred_locked(inner, &mut guard);
5251 }
5252 out
5253 }
5254 Err(_) => return fallback,
5255 }
5256 };
5257 self.finish_outer_borrow();
5258 result
5259 }
5260
5261 pub fn bind_text<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5273 where
5274 CallbackFn: FnMut() -> String + 'static,
5275 {
5276 let handle: Self = self.clone();
5277 Effect::new(move || {
5278 let value: String = producer();
5279 handle.mutate(move |tree: &mut SceneTree| {
5280 tree.set_text(node_id, value);
5281 });
5282 })
5283 }
5284
5285 pub fn bind_style<CallbackFn>(&self, node_id: NodeId, mut producer: CallbackFn) -> Effect
5297 where
5298 CallbackFn: FnMut() -> Style + 'static,
5299 {
5300 let handle: Self = self.clone();
5301 Effect::new(move || {
5302 let style: Style = producer();
5303 handle.mutate(move |tree: &mut SceneTree| {
5304 tree.set_style(node_id, style);
5305 });
5306 })
5307 }
5308}
5309
5310impl Drop for ContextShared {
5312 fn drop(&mut self) {
5318 let Self {
5319 owned_signals,
5320 runtime_epoch,
5321 ..
5322 } = self;
5323 if *runtime_epoch != current_runtime_epoch() {
5324 return;
5325 }
5326 for sig_id in owned_signals.iter().copied() {
5327 let dropped: SignalSlot = with_runtime(
5328 |runtime_ref: &mut ReactiveRuntime| runtime_ref.dispose_signal(sig_id),
5329 SignalSlot::empty(),
5330 );
5331 drop(dropped);
5332 }
5333 }
5334}
5335
5336impl Context {
5338 #[must_use]
5349 pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
5350 let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
5351 let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
5352 let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
5353 let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
5354 let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
5355 let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
5356 let system_back: Signal<u64> = Signal::new_detached(0);
5357 let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
5358 let live_fps: Signal<f32> = Signal::new_detached(60.0);
5359 let present_fps: Signal<f32> = Signal::new_detached(0.0);
5360 let is_idle: Signal<bool> = Signal::new_detached(true);
5361 let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
5362 let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
5363 let exit_requested: Signal<bool> = Signal::new_detached(false);
5364 let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
5365 let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
5366 let keyboard_visible: Signal<bool> = Signal::new_detached(false);
5367 let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
5368 let orientation: Signal<ScreenOrientation> =
5369 Signal::new_detached(ScreenOrientation::Landscape);
5370 let low_power_mode: Signal<bool> = Signal::new_detached(false);
5371 let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
5372 let window_focused: Signal<bool> = Signal::new_detached(true);
5373 let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
5374 let device_motion: Signal<DeviceMotionSample> =
5375 Signal::new_detached(DeviceMotionSample::default());
5376 let owned_signals: [SignalId; 24] = [
5377 breakpoint.id(),
5378 viewport_size.id(),
5379 theme_mode.id(),
5380 safe_area.id(),
5381 gesture.id(),
5382 swipe_drag_offset.id(),
5383 system_back.id(),
5384 fps_limit.id(),
5385 live_fps.id(),
5386 present_fps.id(),
5387 is_idle.id(),
5388 display_refresh_rate.id(),
5389 active_touches.id(),
5390 exit_requested.id(),
5391 app_state.id(),
5392 network_status.id(),
5393 keyboard_visible.id(),
5394 keyboard_height.id(),
5395 orientation.id(),
5396 low_power_mode.id(),
5397 locale.id(),
5398 window_focused.id(),
5399 immersive_fullscreen.id(),
5400 device_motion.id(),
5401 ];
5402 Self {
5403 scene,
5404 breakpoint,
5405 viewport_size,
5406 theme_mode,
5407 platform,
5408 safe_area,
5409 gesture,
5410 swipe_drag_offset,
5411 system_back,
5412 dynamic_hub: DynamicUpdateHub::new(),
5413 fps_limit,
5414 live_fps,
5415 present_fps,
5416 is_idle,
5417 display_refresh_rate,
5418 active_touches,
5419 exit_requested,
5420 app_state,
5421 network_status,
5422 keyboard_visible,
5423 keyboard_height,
5424 orientation,
5425 low_power_mode,
5426 locale,
5427 window_focused,
5428 immersive_fullscreen,
5429 device_motion,
5430 shared: Rc::new(ContextShared {
5431 fullscreen_depth: Cell::new(0),
5432 clock_ms: Cell::new(0),
5433 owned_signals,
5434 runtime_epoch: current_runtime_epoch(),
5435 }),
5436 }
5437 }
5438
5439 #[must_use]
5449 pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
5450 self.get_safe_area()
5451 }
5452
5453 #[must_use]
5463 pub fn safe_area(&self) -> SafeAreaInsets {
5464 self.get_safe_area().get()
5465 }
5466
5467 #[must_use]
5477 pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
5478 self.get_immersive_fullscreen()
5479 }
5480
5481 #[must_use]
5491 pub fn is_immersive_fullscreen(&self) -> bool {
5492 self.get_immersive_fullscreen().get()
5493 }
5494
5495 pub fn set_immersive_fullscreen(&self, enabled: bool) {
5502 let Self { shared, .. } = self;
5503 let changed: bool = if enabled {
5504 if shared.fullscreen_depth.get() == 0 {
5505 shared.fullscreen_depth.set(1);
5506 }
5507 self.get_immersive_fullscreen().set_if_changed(true)
5508 } else {
5509 shared.fullscreen_depth.set(0);
5510 self.get_immersive_fullscreen().set_if_changed(false)
5511 };
5512 if changed {
5513 notify_frame_needed();
5514 }
5515 }
5516
5517 pub fn enter_immersive_fullscreen(&self) {
5523 let Self { shared, .. } = self;
5524 let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
5525 shared.fullscreen_depth.set(next);
5526 if self.get_immersive_fullscreen().set_if_changed(true) {
5527 notify_frame_needed();
5528 }
5529 }
5530
5531 pub fn exit_immersive_fullscreen(&self) {
5537 let Self { shared, .. } = self;
5538 let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
5539 shared.fullscreen_depth.set(next);
5540 if next == 0 && self.get_immersive_fullscreen().set_if_changed(false) {
5541 notify_frame_needed();
5542 }
5543 }
5544
5545 #[must_use]
5555 pub fn app_state_signal(&self) -> Signal<AppState> {
5556 self.get_app_state()
5557 }
5558
5559 pub fn emit_page_appear(&self) {
5565 let system_event: SystemEvent = SystemEvent::Appear;
5566 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5567 .get_scene()
5568 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5569 dispatch_lifecycle_system_event(&observers, &system_event);
5570 dispatch_system_event_listeners(&system_event);
5571 }
5572
5573 pub fn emit_page_disappear(&self) {
5579 let system_event: SystemEvent = SystemEvent::Disappear;
5580 let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5581 .get_scene()
5582 .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5583 dispatch_lifecycle_system_event(&observers, &system_event);
5584 dispatch_system_event_listeners(&system_event);
5585 }
5586
5587 pub fn emit_subtree_appear(&self, root: NodeId) {
5594 self.get_scene().emit_subtree_appear(root);
5595 }
5596
5597 pub fn emit_subtree_disappear(&self, root: NodeId) {
5604 self.get_scene().emit_subtree_disappear(root);
5605 }
5606
5607 #[must_use]
5617 pub fn elapsed_ms(&self) -> u64 {
5618 let Self { shared, .. } = self;
5619 shared.clock_ms.get()
5620 }
5621
5622 pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
5629 let Self { shared, .. } = self;
5630 shared
5631 .clock_ms
5632 .set(shared.clock_ms.get().saturating_add(delta_ms));
5633 }
5634
5635 pub fn request_exit(&self) {
5641 let _: bool = self.get_exit_requested().set_if_changed(true);
5642 let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
5643 }
5644
5645 pub fn copy_to_clipboard(&self, text: &str) -> bool {
5656 write_system_clipboard(text)
5657 }
5658
5659 pub fn view(&mut self, style: Style) -> NodeId {
5670 self.get_scene().with_write(
5671 |tree: &mut SceneTree| tree.create_view(style),
5672 NodeId::default(),
5673 )
5674 }
5675
5676 pub fn text(&mut self, content: String, style: Style) -> NodeId {
5688 self.get_scene().with_write(
5689 |tree: &mut SceneTree| tree.create_text(content, style),
5690 NodeId::default(),
5691 )
5692 }
5693
5694 pub fn reactive_text<CallbackFn>(&mut self, style: Style, producer: CallbackFn) -> NodeId
5706 where
5707 CallbackFn: FnMut() -> String + 'static,
5708 {
5709 let node_id: NodeId = self.text(String::new(), style);
5710 let handle: SceneHandle = self.get_scene().clone();
5711 let (scope, _): (Scope, Effect) =
5712 Scope::run(|_: Scope| handle.bind_text(node_id, producer));
5713 self.get_scene().with_write(
5714 |tree: &mut SceneTree| {
5715 tree.attach_scope(node_id, scope);
5716 },
5717 (),
5718 );
5719 node_id
5720 }
5721
5722 pub fn scroll_view(&mut self, style: Style) -> NodeId {
5733 self.get_scene().with_write(
5734 |tree: &mut SceneTree| tree.create_scroll_view(style),
5735 NodeId::default(),
5736 )
5737 }
5738
5739 pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
5751 self.get_scene().with_write(
5752 |tree: &mut SceneTree| tree.create_input(state, style),
5753 NodeId::default(),
5754 )
5755 }
5756
5757 pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
5769 self.get_scene().with_write(
5770 |tree: &mut SceneTree| tree.create_image(buffer, style),
5771 NodeId::default(),
5772 )
5773 }
5774
5775 pub fn canvas<CallbackFn>(&mut self, style: Style, painter: CallbackFn) -> NodeId
5787 where
5788 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5789 {
5790 self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
5791 }
5792
5793 pub fn canvas_with_caching<CallbackFn>(
5806 &mut self,
5807 style: Style,
5808 caching: CanvasCaching,
5809 painter: CallbackFn,
5810 ) -> NodeId
5811 where
5812 CallbackFn: FnMut(Rect, &mut DisplayList) + 'static,
5813 {
5814 let callback_fn: CanvasDrawCallback = Rc::new(RefCell::new(painter));
5815 self.get_scene().with_write(
5816 |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, callback_fn),
5817 NodeId::default(),
5818 )
5819 }
5820
5821 pub fn portal(&mut self, style: Style) -> NodeId {
5832 self.get_scene().with_write(
5833 |tree: &mut SceneTree| tree.create_portal(style),
5834 NodeId::default(),
5835 )
5836 }
5837
5838 pub fn fragment(&mut self) -> NodeId {
5848 self.get_scene().with_write(
5849 |tree: &mut SceneTree| tree.create_fragment(),
5850 NodeId::default(),
5851 )
5852 }
5853
5854 pub fn append(&mut self, parent: NodeId, child: NodeId) {
5862 self.get_scene().with_write(
5863 |tree: &mut SceneTree| {
5864 tree.append_child(parent, child);
5865 },
5866 (),
5867 );
5868 }
5869
5870 pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
5878 if children.is_empty() {
5879 return;
5880 }
5881 self.get_scene().with_write(
5882 |tree: &mut SceneTree| {
5883 tree.append_children(parent, children);
5884 },
5885 (),
5886 );
5887 }
5888
5889 pub fn bind_style<CallbackFn>(&mut self, node_id: NodeId, producer: CallbackFn)
5897 where
5898 CallbackFn: FnMut() -> Style + 'static,
5899 {
5900 let handle: SceneHandle = self.get_scene().clone();
5901 let (scope, _): (Scope, Effect) =
5902 Scope::run(|_: Scope| handle.bind_style(node_id, producer));
5903 self.get_scene().with_write(
5904 |tree: &mut SceneTree| {
5905 tree.attach_scope(node_id, scope);
5906 },
5907 (),
5908 );
5909 }
5910
5911 pub fn on_pointer_enter<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5919 where
5920 CallbackFn: FnMut(&UiEvent) + 'static,
5921 {
5922 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5923 self.get_scene().with_write(
5924 |tree: &mut SceneTree| {
5925 if let Some(node) = tree.get_node_mut(node_id) {
5926 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5927 }
5928 },
5929 (),
5930 );
5931 }
5932
5933 pub fn on_pointer_leave<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5941 where
5942 CallbackFn: FnMut(&UiEvent) + 'static,
5943 {
5944 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5945 self.get_scene().with_write(
5946 |tree: &mut SceneTree| {
5947 if let Some(node) = tree.get_node_mut(node_id) {
5948 node.get_mut_handlers().set_on_pointer_leave(Some(handler));
5949 }
5950 },
5951 (),
5952 );
5953 }
5954
5955 pub fn on_focus<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5963 where
5964 CallbackFn: FnMut(&UiEvent) + 'static,
5965 {
5966 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5967 self.get_scene().with_write(
5968 |tree: &mut SceneTree| {
5969 if let Some(node) = tree.get_node_mut(node_id) {
5970 node.get_mut_handlers().set_on_focus(Some(handler));
5971 node.get_mut_interaction().set_focusable(true);
5972 }
5973 },
5974 (),
5975 );
5976 }
5977
5978 pub fn on_blur<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
5986 where
5987 CallbackFn: FnMut(&UiEvent) + 'static,
5988 {
5989 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5990 self.get_scene().with_write(
5991 |tree: &mut SceneTree| {
5992 if let Some(node) = tree.get_node_mut(node_id) {
5993 node.get_mut_handlers().set_on_blur(Some(handler));
5994 }
5995 },
5996 (),
5997 );
5998 }
5999
6000 pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
6008 self.get_scene().with_write(
6009 |tree: &mut SceneTree| {
6010 if let Some(node) = tree.get_node_mut(node_id) {
6011 node.get_mut_interaction().set_focusable(focusable);
6012 }
6013 },
6014 (),
6015 );
6016 }
6017
6018 pub fn on_click<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6026 where
6027 CallbackFn: FnMut(&UiEvent) + 'static,
6028 {
6029 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6030 self.get_scene().with_write(
6031 |tree: &mut SceneTree| {
6032 if let Some(node) = tree.get_node_mut(node_id) {
6033 node.get_mut_handlers().set_on_click(Some(handler));
6034 node.get_mut_interaction().set_focusable(true);
6035 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
6036 if paint.get_cursor() == CursorIcon::Default {
6037 paint.set_cursor(CursorIcon::Pointer);
6038 }
6039 }
6040 },
6041 (),
6042 );
6043 }
6044
6045 pub fn on_change<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6053 where
6054 CallbackFn: FnMut(&UiEvent) + 'static,
6055 {
6056 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6057 self.get_scene().with_write(
6058 |tree: &mut SceneTree| {
6059 if let Some(node) = tree.get_node_mut(node_id) {
6060 node.get_mut_handlers().set_on_change(Some(handler));
6061 }
6062 },
6063 (),
6064 );
6065 }
6066
6067 pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
6075 self.get_scene().with_write(
6076 |tree: &mut SceneTree| {
6077 if let Some(node) = tree.get_node_mut(node_id) {
6078 node.set_a11y(Some(props));
6079 }
6080 },
6081 (),
6082 );
6083 }
6084
6085 pub fn on_scroll<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6093 where
6094 CallbackFn: FnMut(&UiEvent) + 'static,
6095 {
6096 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6097 self.get_scene().with_write(
6098 |tree: &mut SceneTree| {
6099 if let Some(node) = tree.get_node_mut(node_id) {
6100 node.get_mut_handlers().set_on_scroll(Some(handler));
6101 }
6102 },
6103 (),
6104 );
6105 }
6106
6107 pub fn on_pointer_down<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6115 where
6116 CallbackFn: FnMut(&UiEvent) + 'static,
6117 {
6118 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6119 self.get_scene().with_write(
6120 |tree: &mut SceneTree| {
6121 if let Some(node) = tree.get_node_mut(node_id) {
6122 node.get_mut_handlers().set_on_pointer_down(Some(handler));
6123 let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
6124 if paint.get_cursor() == CursorIcon::Default {
6125 paint.set_cursor(CursorIcon::Pointer);
6126 }
6127 }
6128 },
6129 (),
6130 );
6131 }
6132
6133 pub fn on_pointer_move<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6141 where
6142 CallbackFn: FnMut(&UiEvent) + 'static,
6143 {
6144 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6145 self.get_scene().with_write(
6146 |tree: &mut SceneTree| {
6147 if let Some(node) = tree.get_node_mut(node_id) {
6148 node.get_mut_handlers().set_on_pointer_move(Some(handler));
6149 }
6150 },
6151 (),
6152 );
6153 }
6154
6155 pub fn on_pointer_up<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6163 where
6164 CallbackFn: FnMut(&UiEvent) + 'static,
6165 {
6166 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6167 self.get_scene().with_write(
6168 |tree: &mut SceneTree| {
6169 if let Some(node) = tree.get_node_mut(node_id) {
6170 node.get_mut_handlers().set_on_pointer_up(Some(handler));
6171 }
6172 },
6173 (),
6174 );
6175 }
6176
6177 pub fn on_pointer_cancel<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6185 where
6186 CallbackFn: FnMut(&UiEvent) + 'static,
6187 {
6188 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6189 self.get_scene().with_write(
6190 |tree: &mut SceneTree| {
6191 if let Some(node) = tree.get_node_mut(node_id) {
6192 node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
6193 }
6194 },
6195 (),
6196 );
6197 }
6198
6199 pub fn on_hover<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6207 where
6208 CallbackFn: FnMut(&UiEvent) + 'static,
6209 {
6210 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6211 let leave_handler: UiEventHandler = handler.clone();
6212 self.get_scene().with_write(
6213 |tree: &mut SceneTree| {
6214 if let Some(node) = tree.get_node_mut(node_id) {
6215 node.get_mut_handlers().set_on_pointer_enter(Some(handler));
6216 node.get_mut_handlers()
6217 .set_on_pointer_leave(Some(leave_handler));
6218 }
6219 },
6220 (),
6221 );
6222 }
6223
6224 pub fn on_key<CallbackFn>(&mut self, node_id: NodeId, callback: CallbackFn)
6232 where
6233 CallbackFn: FnMut(&UiEvent) + 'static,
6234 {
6235 let handler: UiEventHandler = Rc::new(RefCell::new(callback));
6236 self.get_scene().with_write(
6237 |tree: &mut SceneTree| {
6238 if let Some(node) = tree.get_node_mut(node_id) {
6239 node.get_mut_handlers().set_on_key_down(Some(handler));
6240 node.get_mut_interaction().set_focusable(true);
6241 }
6242 },
6243 (),
6244 );
6245 }
6246
6247 pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
6256 self.get_scene()
6257 .set_virtual_scroll(node_id, scroll_y, content_height);
6258 }
6259
6260 pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
6268 self.get_scene().with_write(
6269 |tree: &mut SceneTree| {
6270 tree.set_scroll_offset(node_id, offset);
6271 },
6272 (),
6273 );
6274 }
6275
6276 pub fn start_transition(&mut self, transition: NodeTransition) {
6283 self.get_scene().start_transition(transition);
6284 }
6285
6286 pub fn bind_children<CallbackFn>(&mut self, host: NodeId, mut builder: CallbackFn)
6294 where
6295 CallbackFn: FnMut() -> Vec<NodeId> + 'static,
6296 {
6297 let ctx_clone: Self = self.clone();
6298 let handle: SceneHandle = self.get_scene().clone();
6299 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6300 Effect::new(move || {
6301 let (child_scope, children): (Scope, Vec<NodeId>) =
6302 Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
6303 let first_opt: Option<NodeId> = children.first().copied();
6304 handle.replace_children_safe(host, children);
6305 if let Some(first) = first_opt {
6306 handle.mutate(move |tree: &mut SceneTree| {
6307 tree.attach_scope(first, child_scope);
6308 });
6309 } else {
6310 child_scope.dispose();
6311 }
6312 })
6313 });
6314 self.get_scene().mutate(move |tree: &mut SceneTree| {
6315 tree.attach_scope(host, scope);
6316 });
6317 }
6318
6319 pub fn bind_children_keyed<ValueType, KeyType, Items, KeyFn, RenderFn>(
6329 &mut self,
6330 host: NodeId,
6331 mut items_fn: Items,
6332 mut key_fn: KeyFn,
6333 mut render_fn: RenderFn,
6334 ) where
6335 ValueType: 'static,
6336 KeyType: Eq + Hash + 'static,
6337 Items: FnMut() -> Vec<ValueType> + 'static,
6338 KeyFn: FnMut(&ValueType) -> KeyType + 'static,
6339 RenderFn: FnMut(ValueType) -> NodeId + 'static,
6340 {
6341 let ctx_clone: Self = self.clone();
6342 let handle: SceneHandle = self.get_scene().clone();
6343 let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
6344 let mut live_nodes: HashMap<KeyType, NodeId> = HashMap::new();
6345 Effect::new(move || {
6346 let next_items: Vec<ValueType> = items_fn();
6347 let mut next_map: HashMap<KeyType, NodeId> =
6348 HashMap::with_capacity(next_items.len());
6349 let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
6350 let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
6351 for item in next_items.into_iter() {
6352 let key: KeyType = key_fn(&item);
6353 if let Some(existing_id) = live_nodes.remove(&key) {
6354 next_children.push(existing_id);
6355 let _: Option<NodeId> = next_map.insert(key, existing_id);
6356 } else {
6357 let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
6358 with_context(ctx_clone.clone(), || render_fn(item))
6359 });
6360 new_scopes.push((mounted_id, item_scope));
6361 next_children.push(mounted_id);
6362 let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
6363 }
6364 }
6365 live_nodes = next_map;
6366 handle.replace_children_safe(host, next_children);
6367 if !new_scopes.is_empty() {
6368 handle.mutate(move |tree: &mut SceneTree| {
6369 for (nid, item_scope) in new_scopes.into_iter() {
6370 tree.attach_scope(nid, item_scope);
6371 }
6372 });
6373 }
6374 })
6375 });
6376 self.get_scene().mutate(move |tree: &mut SceneTree| {
6377 tree.attach_scope(host, scope);
6378 });
6379 }
6380}
6381
6382impl Drop for ContextGuard {
6384 fn drop(&mut self) {
6390 let Self { previous } = self;
6391 let restored: Option<Context> = previous.take();
6392 ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
6393 *slot.borrow_mut() = restored;
6394 });
6395 }
6396}
6397
6398impl NodeRefTarget for NodeId {
6400 fn bind_node_ref(&mut self, id: NodeId) {
6407 *self = id;
6408 }
6409}
6410
6411impl NodeRefTarget for Option<NodeId> {
6413 fn bind_node_ref(&mut self, id: NodeId) {
6420 *self = Some(id);
6421 }
6422}
6423
6424impl NodeRefTarget for Cell<NodeId> {
6426 fn bind_node_ref(&mut self, id: NodeId) {
6433 self.set(id);
6434 }
6435}
6436
6437impl NodeRefTarget for Rc<Cell<NodeId>> {
6439 fn bind_node_ref(&mut self, id: NodeId) {
6446 self.set(id);
6447 }
6448}
6449
6450impl NodeRefTarget for Cell<Option<NodeId>> {
6452 fn bind_node_ref(&mut self, id: NodeId) {
6459 self.set(Some(id));
6460 }
6461}
6462
6463impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
6465 fn bind_node_ref(&mut self, id: NodeId) {
6472 self.set(Some(id));
6473 }
6474}
6475
6476impl TextNodeContent for String {
6478 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6490 ctx.text(self, style)
6491 }
6492
6493 fn mount_text_current(self, style: Style) -> NodeId {
6504 with_current_context(|ctx: &Context| {
6505 ctx.get_scene().with_write(
6506 |tree: &mut SceneTree| tree.create_text(self, style),
6507 NodeId::default(),
6508 )
6509 })
6510 }
6511}
6512
6513impl TextNodeContent for &str {
6515 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6527 ctx.text(self.to_string(), style)
6528 }
6529
6530 fn mount_text_current(self, style: Style) -> NodeId {
6541 let owned: String = self.to_string();
6542 with_current_context(|ctx: &Context| {
6543 ctx.get_scene().with_write(
6544 |tree: &mut SceneTree| tree.create_text(owned, style),
6545 NodeId::default(),
6546 )
6547 })
6548 }
6549}
6550
6551impl TextNodeContent for &String {
6553 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6565 ctx.text(self.clone(), style)
6566 }
6567
6568 fn mount_text_current(self, style: Style) -> NodeId {
6579 let owned: String = self.clone();
6580 with_current_context(|ctx: &Context| {
6581 ctx.get_scene().with_write(
6582 |tree: &mut SceneTree| tree.create_text(owned, style),
6583 NodeId::default(),
6584 )
6585 })
6586 }
6587}
6588
6589impl TextNodeContent for Cow<'_, str> {
6591 fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6603 ctx.text(self.into_owned(), style)
6604 }
6605
6606 fn mount_text_current(self, style: Style) -> NodeId {
6617 let owned: String = self.into_owned();
6618 with_current_context(|ctx: &Context| {
6619 ctx.get_scene().with_write(
6620 |tree: &mut SceneTree| tree.create_text(owned, style),
6621 NodeId::default(),
6622 )
6623 })
6624 }
6625}
6626
6627impl<CallbackFn, TextValue> TextNodeContent for CallbackFn
6629where
6630 CallbackFn: FnMut() -> TextValue + 'static,
6631 TextValue: Into<String>,
6632{
6633 fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
6645 ctx.reactive_text(style, move || self().into())
6646 }
6647
6648 fn mount_text_current(mut self, style: Style) -> NodeId {
6659 mount_reactive_text(style, move || self().into())
6660 }
6661}