1use std::any::{Any, TypeId};
6use std::fmt::{self, Debug, Display};
7use std::rc::Rc;
8
9use indexmap::IndexMap;
10use waft_embedder::{Matrix4, Offset};
11use waft_foundation::{
12 App, DiagnosticPropertiesBuilder, DiagnosticableTreeNode, DiagnosticsNode,
13 DiagnosticsTreeStyle, Handle, display_or_null, message,
14};
15use waft_painting::{Axis, AxisDirection};
16
17use crate::box_::{AnyRenderBox, BoxConstraints, BoxHitTestResult};
18use crate::object::{
19 AnyRenderObject, ContainerParentData, ContainerParentDataMixin, ContainerRenderObjectBase,
20 ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject, zero_matrix,
21};
22use crate::painting_context::PaintingContext;
23use crate::pipeline_owner::PipelineOwner;
24use crate::sliver::{
25 RenderSliver, RenderSliverHelpers, SliverConstraints, SliverHitTestResult,
26 SliverLogicalParentData, apply_growth_direction_to_axis_direction,
27};
28
29pub trait RenderSliverBoxChildManager {
39 fn create_child(&self, app: &mut App, index: i32, after: Option<AnyRenderBox>);
61
62 fn remove_child(&self, app: &mut App, child: AnyRenderBox);
70
71 fn estimate_max_scroll_offset(
76 &self,
77 app: &App,
78 constraints: SliverConstraints,
79 first_index: Option<i32>,
80 last_index: Option<i32>,
81 leading_scroll_offset: Option<f64>,
82 trailing_scroll_offset: Option<f64>,
83 ) -> f64;
84
85 fn child_count(&self, app: &mut App) -> i32;
94
95 fn estimated_child_count(&self, app: &App) -> Option<i32> {
98 let _ = app;
99 None
100 }
101
102 fn did_adopt_child(&self, app: &mut App, child: AnyRenderBox);
109
110 fn set_did_underflow(&self, app: &mut App, value: bool);
118
119 fn did_start_layout(&self, app: &mut App) {
121 let _ = app;
122 }
123
124 fn did_finish_layout(&self, app: &mut App) {
126 let _ = app;
127 }
128
129 fn debug_assert_child_list_locked(&self, app: &App) -> bool {
134 let _ = app;
135 true
136 }
137}
138
139#[derive(Clone, Copy, Debug, Default)]
144pub struct KeepAliveParentData {
145 pub keep_alive: bool,
147 kept_alive: bool,
148}
149
150impl KeepAliveParentData {
151 pub const fn new() -> KeepAliveParentData {
153 KeepAliveParentData {
154 keep_alive: false,
155 kept_alive: false,
156 }
157 }
158
159 pub fn kept_alive(&self) -> bool {
162 self.kept_alive
163 }
164}
165
166pub trait RenderSliverWithKeepAliveMixin: RenderSliver {
171 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
174 let _ = self;
175 debug_assert!(
176 child
177 .parent_data(app)
178 .is_some_and(|parent_data| parent_data.part::<KeepAliveParentData>().is_some())
179 );
180 }
181}
182
183#[derive(Debug)]
185pub struct SliverMultiBoxAdaptorParentData {
186 sliver_logical: SliverLogicalParentData,
187 container: ContainerParentData<AnyRenderBox>,
188 keep_alive: KeepAliveParentData,
189 pub index: Option<i32>,
191}
192
193impl SliverMultiBoxAdaptorParentData {
194 pub const fn new() -> SliverMultiBoxAdaptorParentData {
196 SliverMultiBoxAdaptorParentData {
197 sliver_logical: SliverLogicalParentData::new(),
198 container: ContainerParentData::new(),
199 keep_alive: KeepAliveParentData::new(),
200 index: None,
201 }
202 }
203
204 pub fn layout_offset(&self) -> Option<f64> {
206 self.sliver_logical.layout_offset
207 }
208
209 pub fn set_layout_offset(&mut self, value: Option<f64>) {
211 self.sliver_logical.layout_offset = value;
212 }
213
214 pub fn keep_alive(&self) -> bool {
216 self.keep_alive.keep_alive
217 }
218
219 pub fn set_keep_alive(&mut self, value: bool) {
221 self.keep_alive.keep_alive = value;
222 }
223
224 pub fn kept_alive(&self) -> bool {
226 self.keep_alive.kept_alive
227 }
228}
229
230impl Default for SliverMultiBoxAdaptorParentData {
231 fn default() -> SliverMultiBoxAdaptorParentData {
232 SliverMultiBoxAdaptorParentData::new()
233 }
234}
235
236impl ParentData for SliverMultiBoxAdaptorParentData {
237 fn detach(&mut self) {
238 ContainerParentDataMixin::detach(self);
239 }
240
241 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
242 if id == TypeId::of::<SliverMultiBoxAdaptorParentData>() {
243 return Some(self);
244 }
245 if id == TypeId::of::<KeepAliveParentData>() {
246 return Some(&self.keep_alive);
247 }
248 self.sliver_logical.provide(id)
249 }
250
251 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
252 if id == TypeId::of::<SliverMultiBoxAdaptorParentData>() {
253 return Some(self);
254 }
255 if id == TypeId::of::<KeepAliveParentData>() {
256 return Some(&mut self.keep_alive);
257 }
258 self.sliver_logical.provide_mut(id)
259 }
260}
261
262impl ContainerParentDataMixin for SliverMultiBoxAdaptorParentData {
263 type ChildType = AnyRenderBox;
264
265 fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
266 &self.container
267 }
268
269 fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
270 &mut self.container
271 }
272}
273
274impl Display for SliverMultiBoxAdaptorParentData {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 write!(f, "index={}; ", display_or_null(&self.index))?;
277 if self.keep_alive() {
278 f.write_str("keepAlive; ")?;
279 }
280 Display::fmt(&self.sliver_logical, f)
281 }
282}
283
284fn restore_parent_data<T: RenderSliverMultiBoxAdaptor>(
293 sliver: RenderHandle<T>,
294 app: &mut App,
295 child: AnyRenderBox,
296 saved: KeptSlot,
297) {
298 RenderObject::setup_parent_data(sliver, app, child.as_object());
299 let restored = child
300 .as_object()
301 .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app);
302 restored.set_layout_offset(saved.layout_offset);
303 restored.set_keep_alive(saved.keep_alive);
304 restored.index = saved.index;
305 restored.keep_alive.kept_alive = true;
306}
307
308#[derive(Clone, Copy)]
311struct KeptSlot {
312 layout_offset: Option<f64>,
313 keep_alive: bool,
314 index: Option<i32>,
315}
316
317impl KeptSlot {
318 fn of(parent_data: &SliverMultiBoxAdaptorParentData) -> KeptSlot {
319 KeptSlot {
320 layout_offset: parent_data.layout_offset(),
321 keep_alive: parent_data.keep_alive(),
322 index: parent_data.index,
323 }
324 }
325}
326
327pub struct RenderSliverMultiBoxAdaptorData {
329 child_manager: Rc<dyn RenderSliverBoxChildManager>,
330 keep_alive_bucket: IndexMap<i32, AnyRenderBox>,
332 debug_dangling_keep_alives: Vec<AnyRenderBox>,
333 debug_child_integrity_enabled: bool,
334}
335
336impl RenderSliverMultiBoxAdaptorData {
337 pub fn new(
339 child_manager: Rc<dyn RenderSliverBoxChildManager>,
340 ) -> RenderSliverMultiBoxAdaptorData {
341 RenderSliverMultiBoxAdaptorData {
342 child_manager,
343 keep_alive_bucket: IndexMap::new(),
344 debug_dangling_keep_alives: Vec::new(),
345 debug_child_integrity_enabled: true,
346 }
347 }
348}
349
350#[macro_export]
352macro_rules! render_sliver_multi_box_adaptor_accessors {
353 () => {
354 fn adaptor_data(
355 self: $crate::RenderHandle<Self>,
356 app: &::waft_foundation::App,
357 ) -> &$crate::RenderSliverMultiBoxAdaptorData {
358 &self.get(app).adaptor
359 }
360 fn adaptor_data_mut(
361 self: $crate::RenderHandle<Self>,
362 app: &mut ::waft_foundation::App,
363 ) -> &mut $crate::RenderSliverMultiBoxAdaptorData {
364 &mut self.get_mut(app).adaptor
365 }
366 };
367}
368
369pub trait RenderSliverMultiBoxAdaptor:
392 RenderSliver
393 + RenderSliverHelpers
394 + RenderSliverWithKeepAliveMixin
395 + ContainerRenderObjectMixin<
396 ChildType = AnyRenderBox,
397 ParentDataType = SliverMultiBoxAdaptorParentData,
398 >
399{
400 fn adaptor_data(self: RenderHandle<Self>, app: &App) -> &RenderSliverMultiBoxAdaptorData;
402
403 fn adaptor_data_mut(
405 self: RenderHandle<Self>,
406 app: &mut App,
407 ) -> &mut RenderSliverMultiBoxAdaptorData;
408
409 fn child_manager(self: RenderHandle<Self>, app: &App) -> Rc<dyn RenderSliverBoxChildManager> {
415 Rc::clone(&self.adaptor_data(app).child_manager)
416 }
417
418 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
420 if !child.parent_data_is::<SliverMultiBoxAdaptorParentData>(app) {
421 child.set_parent_data(app, SliverMultiBoxAdaptorParentData::new());
422 }
423 }
424
425 fn debug_child_integrity_enabled(self: RenderHandle<Self>, app: &App) -> bool {
433 self.adaptor_data(app).debug_child_integrity_enabled
434 }
435
436 fn set_debug_child_integrity_enabled(self: RenderHandle<Self>, app: &mut App, enabled: bool) {
439 if !cfg!(debug_assertions) {
440 return;
441 }
442 self.adaptor_data_mut(app).debug_child_integrity_enabled = enabled;
443 debug_assert!(self.debug_verify_child_order(app));
444 debug_assert!(
445 !enabled || self.adaptor_data(app).debug_dangling_keep_alives.is_empty(),
446 "a keep-alive child was left dangling by move_child"
447 );
448 }
449
450 fn debug_assert_child_list_locked(self: RenderHandle<Self>, app: &App) -> bool {
452 self.child_manager(app).debug_assert_child_list_locked(app)
453 }
454
455 fn debug_verify_child_order(self: RenderHandle<Self>, app: &App) -> bool {
459 if self.debug_child_integrity_enabled(app) {
460 let mut child = self.first_child(app);
461 while let Some(current) = child {
462 let index = self.index_of(app, current);
463 child = self.child_after(app, current);
464 debug_assert!(child.is_none_or(|next| self.index_of(app, next) > index));
465 }
466 }
467 true
468 }
469
470 fn insert(
472 self: RenderHandle<Self>,
473 app: &mut App,
474 child: AnyRenderBox,
475 after: Option<AnyRenderBox>,
476 ) {
477 debug_assert!(
478 !self
479 .adaptor_data(app)
480 .keep_alive_bucket
481 .values()
482 .any(|kept| *kept == child)
483 );
484 ContainerRenderObjectBase::insert(self, app, child, after);
485 self.did_adopt_child(app, child);
486 debug_assert!(self.first_child(app).is_some());
487 debug_assert!(self.debug_verify_child_order(app));
488 }
489
490 fn did_adopt_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
496 let kept_alive = child
497 .as_object()
498 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
499 .kept_alive();
500 if !kept_alive {
501 self.child_manager(app).did_adopt_child(app, child);
502 }
503 }
504
505 fn move_child(
517 self: RenderHandle<Self>,
518 app: &mut App,
519 child: AnyRenderBox,
520 after: Option<AnyRenderBox>,
521 ) {
522 let child_parent_data = child
523 .as_object()
524 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
525 let (kept_alive, index) = (child_parent_data.kept_alive(), child_parent_data.index);
526 if !kept_alive {
527 ContainerRenderObjectBase::move_child(self, app, child, after);
528 self.child_manager(app).did_adopt_child(app, child);
530 self.mark_needs_layout(app);
533 return;
534 }
535 if let Some(index) = index
538 && self.adaptor_data(app).keep_alive_bucket.get(&index) == Some(&child)
539 {
540 self.adaptor_data_mut(app)
541 .keep_alive_bucket
542 .shift_remove(&index);
543 }
544 if cfg!(debug_assertions) {
545 self.adaptor_data_mut(app)
546 .debug_dangling_keep_alives
547 .retain(|dangling| *dangling != child);
548 }
549 self.child_manager(app).did_adopt_child(app, child);
551 let new_index = child
555 .as_object()
556 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
557 .index
558 .expect("did_adopt_child sets the index");
559 if cfg!(debug_assertions)
560 && let Some(existing) = self
561 .adaptor_data(app)
562 .keep_alive_bucket
563 .get(&new_index)
564 .copied()
565 {
566 self.adaptor_data_mut(app)
567 .debug_dangling_keep_alives
568 .push(existing);
569 }
570 self.adaptor_data_mut(app)
571 .keep_alive_bucket
572 .insert(new_index, child);
573 }
574
575 fn remove(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
577 let child_parent_data = child
578 .as_object()
579 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
580 let (kept_alive, index) = (child_parent_data.kept_alive(), child_parent_data.index);
581 if !kept_alive {
582 ContainerRenderObjectBase::remove(self, app, child);
583 return;
584 }
585 let index = index.expect("a kept-alive child has an index");
586 debug_assert_eq!(
587 self.adaptor_data(app).keep_alive_bucket.get(&index),
588 Some(&child)
589 );
590 if cfg!(debug_assertions) {
591 self.adaptor_data_mut(app)
592 .debug_dangling_keep_alives
593 .retain(|dangling| *dangling != child);
594 }
595 self.adaptor_data_mut(app)
596 .keep_alive_bucket
597 .shift_remove(&index);
598 self.drop_child(app, child.as_object());
599 }
600
601 fn remove_all(self: RenderHandle<Self>, app: &mut App) {
603 ContainerRenderObjectBase::remove_all(self, app);
604 for child in self.keep_alive_children(app) {
605 self.drop_child(app, child.as_object());
606 }
607 self.adaptor_data_mut(app).keep_alive_bucket.clear();
608 }
609
610 fn keep_alive_children(self: RenderHandle<Self>, app: &App) -> Vec<AnyRenderBox> {
612 self.adaptor_data(app)
613 .keep_alive_bucket
614 .values()
615 .copied()
616 .collect()
617 }
618
619 fn create_or_obtain_child(
621 self: RenderHandle<Self>,
622 app: &mut App,
623 index: i32,
624 after: Option<AnyRenderBox>,
625 ) {
626 self.as_object().invoke_layout_callback(app, |app| {
627 let cached = self
628 .adaptor_data(app)
629 .keep_alive_bucket
630 .get(&index)
631 .copied();
632 let Some(child) = cached else {
633 self.child_manager(app).create_child(app, index, after);
634 return;
635 };
636 self.adaptor_data_mut(app)
637 .keep_alive_bucket
638 .shift_remove(&index);
639 let child_parent_data = child
640 .as_object()
641 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
642 debug_assert!(child_parent_data.kept_alive());
643 let saved = KeptSlot::of(child_parent_data);
644 self.drop_child(app, child.as_object());
645 restore_parent_data(self, app, child, saved);
646 RenderSliverMultiBoxAdaptor::insert(self, app, child, after);
647 child
648 .as_object()
649 .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
650 .keep_alive
651 .kept_alive = false;
652 });
653 }
654
655 fn destroy_or_cache_child(self: RenderHandle<Self>, app: &mut App, child: AnyRenderBox) {
657 let child_parent_data = child
658 .as_object()
659 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
660 if !child_parent_data.keep_alive() {
661 debug_assert_eq!(child.as_object().parent(app), Some(self.as_object()));
662 self.child_manager(app).remove_child(app, child);
663 debug_assert!(child.as_object().parent(app).is_none());
664 return;
665 }
666 debug_assert!(!child_parent_data.kept_alive());
667 let saved = KeptSlot::of(child_parent_data);
668 let index = saved.index.expect("a cached child has an index");
669 RenderSliverMultiBoxAdaptor::remove(self, app, child);
670 self.adaptor_data_mut(app)
671 .keep_alive_bucket
672 .insert(index, child);
673 restore_parent_data(self, app, child, saved);
674 self.as_object().adopt_child(app, child.as_object());
677 }
678
679 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
681 ContainerRenderObjectMixin::did_attach(self, app, owner);
682 for child in self.keep_alive_children(app) {
683 child.as_object().attach(app, owner);
684 }
685 }
686
687 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
689 ContainerRenderObjectMixin::did_detach(self, app);
690 for child in self.keep_alive_children(app) {
691 child.as_object().detach(app);
692 }
693 }
694
695 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
697 ContainerRenderObjectMixin::redepth_children(self, app);
698 for child in self.keep_alive_children(app) {
699 self.as_object().redepth_child(app, child.as_object());
700 }
701 }
702
703 fn visit_children(
705 self: RenderHandle<Self>,
706 app: &App,
707 visitor: &mut dyn FnMut(AnyRenderObject),
708 ) {
709 ContainerRenderObjectMixin::visit_children(self, app, visitor);
710 for child in self.keep_alive_children(app) {
711 visitor(child.as_object());
712 }
713 }
714
715 fn add_initial_child(
726 self: RenderHandle<Self>,
727 app: &mut App,
728 index: i32,
729 layout_offset: f64,
730 ) -> bool {
731 debug_assert!(self.debug_assert_child_list_locked(app));
732 debug_assert!(self.first_child(app).is_none());
733 self.create_or_obtain_child(app, index, None);
734 if let Some(first_child) = self.first_child(app) {
735 debug_assert_eq!(Some(first_child), self.last_child(app));
736 debug_assert_eq!(self.index_of(app, first_child), index);
737 first_child
738 .as_object()
739 .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
740 .set_layout_offset(Some(layout_offset));
741 return true;
742 }
743 self.child_manager(app).set_did_underflow(app, true);
744 false
745 }
746
747 fn insert_and_layout_leading_child(
755 self: RenderHandle<Self>,
756 app: &mut App,
757 child_constraints: BoxConstraints,
758 parent_uses_size: bool,
759 ) -> Option<AnyRenderBox> {
760 debug_assert!(self.debug_assert_child_list_locked(app));
761 let first_child = self.first_child(app).expect("there is a leading child");
762 let index = self.index_of(app, first_child) - 1;
763 self.create_or_obtain_child(app, index, None);
764 let first_child = self.first_child(app).expect("the child list is not empty");
765 if self.index_of(app, first_child) == index {
766 first_child.layout(app, child_constraints, parent_uses_size);
767 return Some(first_child);
768 }
769 self.child_manager(app).set_did_underflow(app, true);
770 None
771 }
772
773 fn insert_and_layout_child(
781 self: RenderHandle<Self>,
782 app: &mut App,
783 child_constraints: BoxConstraints,
784 after: Option<AnyRenderBox>,
785 parent_uses_size: bool,
786 ) -> Option<AnyRenderBox> {
787 debug_assert!(self.debug_assert_child_list_locked(app));
788 let after = after.expect("insert_and_layout_child needs a preceding child");
789 let index = self.index_of(app, after) + 1;
790 self.create_or_obtain_child(app, index, Some(after));
791 let child = self.child_after(app, after);
792 if let Some(child) = child
793 && self.index_of(app, child) == index
794 {
795 child.layout(app, child_constraints, parent_uses_size);
796 return Some(child);
797 }
798 self.child_manager(app).set_did_underflow(app, true);
799 None
800 }
801
802 fn calculate_leading_garbage(self: RenderHandle<Self>, app: &App, first_index: i32) -> usize {
805 let mut walker = self.first_child(app);
806 let mut leading_garbage = 0;
807 while let Some(current) = walker {
808 if self.index_of(app, current) >= first_index {
809 break;
810 }
811 leading_garbage += 1;
812 walker = self.child_after(app, current);
813 }
814 leading_garbage
815 }
816
817 fn calculate_trailing_garbage(self: RenderHandle<Self>, app: &App, last_index: i32) -> usize {
820 let mut walker = self.last_child(app);
821 let mut trailing_garbage = 0;
822 while let Some(current) = walker {
823 if self.index_of(app, current) <= last_index {
824 break;
825 }
826 trailing_garbage += 1;
827 walker = self.child_before(app, current);
828 }
829 trailing_garbage
830 }
831
832 fn collect_garbage(
842 self: RenderHandle<Self>,
843 app: &mut App,
844 leading_garbage: usize,
845 trailing_garbage: usize,
846 ) {
847 debug_assert!(self.debug_assert_child_list_locked(app));
848 debug_assert!(self.child_count(app) >= leading_garbage + trailing_garbage);
849 self.as_object().invoke_layout_callback(app, |app| {
850 for _ in 0..leading_garbage {
851 let first_child = self.first_child(app).expect("counted above");
852 self.destroy_or_cache_child(app, first_child);
853 }
854 for _ in 0..trailing_garbage {
855 let last_child = self.last_child(app).expect("counted above");
856 self.destroy_or_cache_child(app, last_child);
857 }
858 let expired: Vec<AnyRenderBox> = self
862 .keep_alive_children(app)
863 .into_iter()
864 .filter(|child| {
865 !child
866 .as_object()
867 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
868 .keep_alive()
869 })
870 .collect();
871 let child_manager = self.child_manager(app);
872 for child in expired {
873 child_manager.remove_child(app, child);
874 }
875 debug_assert!(self.keep_alive_children(app).iter().all(|child| {
876 child
877 .as_object()
878 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
879 .keep_alive()
880 }));
881 });
882 }
883
884 fn index_of(self: RenderHandle<Self>, app: &App, child: AnyRenderBox) -> i32 {
887 child
888 .as_object()
889 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
890 .index
891 .expect("a reified child has an index")
892 }
893
894 fn debug_fill_properties(
896 self: RenderHandle<Self>,
897 app: &App,
898 properties: &mut DiagnosticPropertiesBuilder,
899 ) {
900 let text = match (self.first_child(app), self.last_child(app)) {
901 (Some(first), Some(last)) => format!(
902 "currently live children: {} to {}",
903 self.index_of(app, first),
904 self.index_of(app, last)
905 ),
906 _ => "no children current live".to_owned(),
907 };
908 properties.add(message(text));
909 }
910
911 fn debug_describe_children(
914 self: RenderHandle<Self>,
915 app: &App,
916 ) -> Vec<Rc<dyn DiagnosticsNode>> {
917 let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
918 if let (Some(mut child), Some(last)) = (self.first_child(app), self.last_child(app)) {
919 loop {
920 let index = self.index_of(app, child);
921 children.push(Rc::new(
922 child
923 .as_object()
924 .to_diagnostics_node(app, format!("child with index {index}")),
925 ));
926 if child == last {
927 break;
928 }
929 child = self
930 .child_after(app, child)
931 .expect("the last child ends the walk");
932 }
933 }
934 let mut indices: Vec<i32> = self
935 .adaptor_data(app)
936 .keep_alive_bucket
937 .keys()
938 .copied()
939 .collect();
940 indices.sort_unstable();
941 for index in indices {
942 let child = self
943 .adaptor_data(app)
944 .keep_alive_bucket
945 .get(&index)
946 .copied()
947 .expect("the index came from the bucket");
948 let name = format!("child with index {index} (kept alive but not laid out)");
949 let node = child.as_object().to_diagnostics_node(app, name.clone());
950 let mut builder =
951 DiagnosticPropertiesBuilder::from_properties(node.properties().to_vec());
952 builder.default_diagnostics_tree_style = DiagnosticsTreeStyle::Offstage;
953 children.push(Rc::new(DiagnosticableTreeNode::from_parts(
954 name,
955 node.description(),
956 builder,
957 node.children().to_vec(),
958 )));
959 }
960 children
961 }
962
963 fn paint_extent_of(self: RenderHandle<Self>, app: &App, child: AnyRenderBox) -> f64 {
967 debug_assert!(child.has_size(app));
968 match self.constraints(app).axis() {
969 Axis::Horizontal => child.size(app).width(),
970 Axis::Vertical => child.size(app).height(),
971 }
972 }
973
974 fn hit_test_children(
976 self: RenderHandle<Self>,
977 app: &mut App,
978 result: &mut SliverHitTestResult<'_>,
979 main_axis_position: f64,
980 cross_axis_position: f64,
981 ) -> bool {
982 let mut child = self.last_child(app);
983 while let Some(current) = child {
984 let previous = self.child_before(app, current);
985 if self.hit_test_box_child(
986 app,
987 &mut BoxHitTestResult::wrap(result),
988 current,
989 main_axis_position,
990 cross_axis_position,
991 ) {
992 return true;
993 }
994 child = previous;
995 }
996 false
997 }
998
999 fn child_main_axis_position(
1001 self: RenderHandle<Self>,
1002 app: &App,
1003 child: AnyRenderObject,
1004 ) -> f64 {
1005 RenderSliverMultiBoxAdaptor::child_scroll_offset(self, app, child)
1006 .expect("a laid-out child has a scroll offset")
1007 - self.constraints(app).scroll_offset
1008 }
1009
1010 fn child_scroll_offset(
1012 self: RenderHandle<Self>,
1013 app: &App,
1014 child: AnyRenderObject,
1015 ) -> Option<f64> {
1016 debug_assert_eq!(child.parent(app), Some(self.as_object()));
1017 child
1018 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1019 .layout_offset()
1020 }
1021
1022 fn paints_child(self: RenderHandle<Self>, app: &App, child: AnyRenderObject) -> bool {
1025 let index = child
1026 .parent_data_is::<SliverMultiBoxAdaptorParentData>(app)
1027 .then(|| {
1028 child
1029 .parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
1030 .index
1031 })
1032 .flatten();
1033 match index {
1034 None => false,
1035 Some(index) => !self
1036 .adaptor_data(app)
1037 .keep_alive_bucket
1038 .contains_key(&index),
1039 }
1040 }
1041
1042 fn apply_paint_transform(
1044 self: RenderHandle<Self>,
1045 app: &App,
1046 child: AnyRenderObject,
1047 transform: &mut Matrix4,
1048 ) {
1049 if RenderObject::paints_child(self, app, child) {
1050 let child = child.as_box().expect("the children are boxes");
1051 self.apply_paint_transform_for_box_child(app, child, transform);
1052 } else {
1053 *transform = zero_matrix();
1060 }
1061 }
1062
1063 fn paint(
1065 self: RenderHandle<Self>,
1066 app: &mut App,
1067 context: &mut PaintingContext,
1068 offset: Offset,
1069 ) {
1070 if self.first_child(app).is_none() {
1071 return;
1072 }
1073 let constraints = self.constraints(app);
1077 let paint_extent = self.geometry(app).paint_extent;
1078 let (main_axis_unit, cross_axis_unit, origin_offset, add_extent) =
1079 match apply_growth_direction_to_axis_direction(
1080 constraints.axis_direction,
1081 constraints.growth_direction,
1082 ) {
1083 AxisDirection::Up => (
1084 Offset::new(0.0, -1.0),
1085 Offset::new(1.0, 0.0),
1086 offset + Offset::new(0.0, paint_extent),
1087 true,
1088 ),
1089 AxisDirection::Right => {
1090 (Offset::new(1.0, 0.0), Offset::new(0.0, 1.0), offset, false)
1091 }
1092 AxisDirection::Down => {
1093 (Offset::new(0.0, 1.0), Offset::new(1.0, 0.0), offset, false)
1094 }
1095 AxisDirection::Left => (
1096 Offset::new(-1.0, 0.0),
1097 Offset::new(0.0, 1.0),
1098 offset + Offset::new(paint_extent, 0.0),
1099 true,
1100 ),
1101 };
1102 let mut child = self.first_child(app);
1103 while let Some(current) = child {
1104 let main_axis_delta = RenderSliverMultiBoxAdaptor::child_main_axis_position(
1105 self,
1106 app,
1107 current.as_object(),
1108 );
1109 let cross_axis_delta = self.child_cross_axis_position(app, current.as_object());
1110 let mut child_offset = Offset::new(
1111 origin_offset.dx()
1112 + main_axis_unit.dx() * main_axis_delta
1113 + cross_axis_unit.dx() * cross_axis_delta,
1114 origin_offset.dy()
1115 + main_axis_unit.dy() * main_axis_delta
1116 + cross_axis_unit.dy() * cross_axis_delta,
1117 );
1118 let child_paint_extent = self.paint_extent_of(app, current);
1119 if add_extent {
1120 child_offset = child_offset + main_axis_unit * child_paint_extent;
1121 }
1122
1123 if main_axis_delta < constraints.remaining_paint_extent
1127 && main_axis_delta + child_paint_extent > 0.0
1128 {
1129 context.paint_child(app, current.as_object(), child_offset);
1130 }
1131
1132 child = self.child_after(app, current);
1133 }
1134 }
1135
1136 fn debug_assert_child_list_is_non_empty_and_contiguous(
1140 self: RenderHandle<Self>,
1141 app: &App,
1142 ) -> bool {
1143 if cfg!(debug_assertions) {
1144 let first_child = self.first_child(app).expect("the child list is not empty");
1145 let mut index = self.index_of(app, first_child);
1146 let mut child = self.child_after(app, first_child);
1147 while let Some(current) = child {
1148 index += 1;
1149 debug_assert_eq!(self.index_of(app, current), index);
1150 child = self.child_after(app, current);
1151 }
1152 }
1153 true
1154 }
1155}
1156
1157#[cfg(test)]
1158pub(crate) mod test_support {
1159 use std::cell::{Cell, RefCell};
1160
1161 use waft_embedder::Size;
1162
1163 use super::*;
1164 use crate::box_::{RenderBox, RenderBoxData};
1165 use crate::object::{RenderObject, RenderObjectData};
1166
1167 pub(crate) struct TestChild {
1169 render_object: RenderObjectData,
1170 render_box: RenderBoxData,
1171 preferred_extent: f64,
1172 }
1173
1174 impl RenderObject for TestChild {
1175 crate::render_object_accessors!();
1176
1177 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1178 let extent = self.get(app).preferred_extent;
1179 let size = self.constraints(app).constrain(Size::new(extent, extent));
1180 self.set_size(app, size);
1181 }
1182 }
1183
1184 impl RenderBox for TestChild {
1185 crate::render_box_accessors!();
1186
1187 fn hit_test_self(self: RenderHandle<Self>, _app: &App, _position: Offset) -> bool {
1188 let _ = self;
1189 true
1190 }
1191 }
1192
1193 pub(crate) fn hit_testable_box(app: &mut App, extent: f64) -> AnyRenderBox {
1196 RenderHandle::new_box(
1197 app,
1198 TestChild {
1199 render_object: RenderObjectData::new(),
1200 render_box: RenderBoxData::new(),
1201 preferred_extent: extent,
1202 },
1203 )
1204 .as_box()
1205 }
1206
1207 pub(crate) struct TestChildManager<T: RenderSliverMultiBoxAdaptor> {
1210 render_object: Cell<Option<RenderHandle<T>>>,
1211 extents: Vec<f64>,
1212 currently_updating_child_index: Cell<Option<i32>>,
1213 pub(crate) created: RefCell<Vec<i32>>,
1215 pub(crate) did_underflow: Cell<bool>,
1217 }
1218
1219 impl<T: RenderSliverMultiBoxAdaptor> TestChildManager<T> {
1220 pub(crate) fn new(extents: Vec<f64>) -> Rc<TestChildManager<T>> {
1221 Rc::new(TestChildManager {
1222 render_object: Cell::new(None),
1223 extents,
1224 currently_updating_child_index: Cell::new(None),
1225 created: RefCell::new(Vec::new()),
1226 did_underflow: Cell::new(false),
1227 })
1228 }
1229
1230 pub(crate) fn attach(&self, render_object: RenderHandle<T>) {
1231 self.render_object.set(Some(render_object));
1232 }
1233
1234 fn adaptor(&self) -> RenderHandle<T> {
1235 self.render_object.get().expect("attached before layout")
1236 }
1237
1238 fn total_extent(&self) -> f64 {
1239 self.extents.iter().sum()
1240 }
1241 }
1242
1243 impl<T: RenderSliverMultiBoxAdaptor> RenderSliverBoxChildManager for TestChildManager<T> {
1244 fn create_child(&self, app: &mut App, index: i32, after: Option<AnyRenderBox>) {
1245 self.created.borrow_mut().push(index);
1246 let Ok(slot) = usize::try_from(index) else {
1247 return;
1248 };
1249 let Some(extent) = self.extents.get(slot).copied() else {
1250 return;
1251 };
1252 let child = RenderHandle::new_box(
1253 app,
1254 TestChild {
1255 render_object: RenderObjectData::new(),
1256 render_box: RenderBoxData::new(),
1257 preferred_extent: extent,
1258 },
1259 )
1260 .as_box();
1261 self.currently_updating_child_index.set(Some(index));
1262 RenderSliverMultiBoxAdaptor::insert(self.adaptor(), app, child, after);
1263 self.currently_updating_child_index.set(None);
1264 }
1265
1266 fn remove_child(&self, app: &mut App, child: AnyRenderBox) {
1267 RenderSliverMultiBoxAdaptor::remove(self.adaptor(), app, child);
1270 }
1271
1272 fn estimate_max_scroll_offset(
1273 &self,
1274 _app: &App,
1275 _constraints: SliverConstraints,
1276 _first_index: Option<i32>,
1277 _last_index: Option<i32>,
1278 _leading_scroll_offset: Option<f64>,
1279 _trailing_scroll_offset: Option<f64>,
1280 ) -> f64 {
1281 self.total_extent()
1282 }
1283
1284 fn child_count(&self, _app: &mut App) -> i32 {
1285 self.extents.len() as i32
1286 }
1287
1288 fn estimated_child_count(&self, _app: &App) -> Option<i32> {
1289 Some(self.extents.len() as i32)
1290 }
1291
1292 fn did_adopt_child(&self, app: &mut App, child: AnyRenderBox) {
1293 child
1294 .as_object()
1295 .parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
1296 .index = self.currently_updating_child_index.get();
1297 }
1298
1299 fn set_did_underflow(&self, _app: &mut App, value: bool) {
1300 self.did_underflow.set(value);
1301 }
1302 }
1303}
1304
1305#[cfg(test)]
1306pub(crate) mod viewport_test_support {
1307 use std::rc::Rc;
1308
1309 use waft_embedder::{Size, View, ViewId, ViewMetrics, ViewRef};
1310 use waft_foundation::{Handle, Ref};
1311
1312 use super::*;
1313 use crate::box_::RenderBox;
1314 use crate::pipeline_owner::PipelineOwner;
1315 use crate::sliver::AnyRenderSliver;
1316 use crate::view::{RenderView, ViewConfiguration};
1317 use crate::viewport::RenderViewport;
1318 use crate::viewport_offset::{FixedViewportOffset, ViewportOffset};
1319 use waft_test::TestViewHost;
1320
1321 #[derive(Default)]
1322 struct TestView {
1323 host: TestViewHost,
1324 }
1325
1326 impl View for TestView {
1327 fn id(&self) -> ViewId {
1328 ViewId(0)
1329 }
1330
1331 fn metrics(&self) -> ViewMetrics {
1332 ViewMetrics::default()
1333 }
1334
1335 fn present(
1336 &self,
1337 _scene: std::sync::Arc<waft_embedder::Scene>,
1338 _size: waft_embedder::Size,
1339 ) {
1340 }
1341
1342 fn host(&self) -> &dyn waft_embedder::ViewHost {
1343 &self.host
1344 }
1345 }
1346
1347 pub(crate) struct ScrollHarness {
1350 pub(crate) owner: Ref<PipelineOwner>,
1351 pub(crate) viewport: RenderHandle<RenderViewport>,
1352 pub(crate) offset: Handle<FixedViewportOffset>,
1353 }
1354
1355 impl ScrollHarness {
1356 pub(crate) fn new(app: &mut App, sliver: AnyRenderSliver, size: Size) -> ScrollHarness {
1358 let offset = FixedViewportOffset::zero(app);
1359 let viewport = RenderViewport::new(
1360 app,
1361 AxisDirection::Right,
1362 offset.erase(),
1363 Some(vec![sliver]),
1364 None,
1365 );
1366 let constraints = BoxConstraints::tight(size);
1367 let configuration = ViewConfiguration::new(constraints, constraints, 1.0);
1368 let view = RenderView::new(
1369 app,
1370 Some(viewport.as_box()),
1371 Some(configuration),
1372 Rc::new(TestView::default()) as ViewRef,
1373 );
1374 let owner = PipelineOwner::new(app, None, None);
1375 owner.set_root_node(app, Some(view.as_object()));
1376 view.prepare_initial_frame(app);
1377 owner.flush_layout(app);
1378 ScrollHarness {
1379 owner,
1380 viewport,
1381 offset: offset.handle(),
1382 }
1383 }
1384
1385 pub(crate) fn scroll_to(&self, app: &mut App, pixels: f64) {
1387 let current = self.offset.pixels(app);
1388 self.offset.correct_by(app, pixels - current);
1389 self.viewport.mark_needs_layout(app);
1390 self.owner.flush_layout(app);
1391 }
1392 }
1393}