use std::any::{Any, TypeId};
use std::collections::{BTreeMap, HashMap};
use std::fmt::{self, Debug};
use std::panic::Location;
use std::rc::Rc;
use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle};
use waft_rendering::{
AnyRenderBox, AnyRenderObject, ItemExtentBuilder, KeepAliveParentData, RenderHandle,
RenderSliver, RenderSliverBoxChildManager, RenderSliverFixedExtentList, RenderSliverGrid,
RenderSliverList, RenderSliverMultiBoxAdaptor, RenderSliverVariedExtentList,
RenderSliverWithKeepAliveMixin, SliverConstraints, SliverGridDelegate,
SliverGridDelegateWithFixedCrossAxisCount, SliverGridDelegateWithMaxCrossAxisExtent,
SliverMultiBoxAdaptorParentData,
};
use crate::framework::{
AnyElement, BuildContext, CreationLocation, Element, ElementData, IntoWidget, KeyRef,
ParentDataWidget, RenderObjectElement, RenderObjectElementData, RenderObjectElementWidget,
RenderObjectWidget, Slot, Widget, WidgetKind, WidgetRef, downcast_widget, short_type_name,
};
use crate::widgets::scroll_delegate::{
ChildIndexGetter, NullableIndexedWidgetBuilder, SemanticIndexCallback,
SliverChildBuilderDelegate, SliverChildDelegateRef, SliverChildListDelegate, same_delegate,
};
pub trait SliverWithKeepAliveWidget: RenderObjectWidget
where
Self::RenderObject: RenderSliverWithKeepAliveMixin,
{
}
pub trait SliverMultiBoxAdaptorWidget: SliverWithKeepAliveWidget
where
Self::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn delegate(&self) -> &SliverChildDelegateRef;
fn debug_fill_properties(&self, properties: &mut DiagnosticPropertiesBuilder) {
properties.add(DiagnosticsProperty::<String>::new(
"delegate",
Some(format!("{:?}", self.delegate())),
));
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
where
Self: Sized,
{
SliverMultiBoxAdaptorElement::<Self>::new(app, this, false).as_element()
}
fn estimate_max_scroll_offset(
&self,
constraints: Option<SliverConstraints>,
first_index: i32,
last_index: i32,
leading_scroll_offset: f64,
trailing_scroll_offset: f64,
) -> Option<f64> {
let _ = constraints;
debug_assert!(last_index >= first_index);
self.delegate().estimate_max_scroll_offset(
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
)
}
}
pub struct SliverMultiBoxAdaptorKind;
pub struct SliverMultiBoxAdaptor<W: SliverMultiBoxAdaptorWidget>(
pub W,
pub(crate) CreationLocation,
)
where
W::RenderObject: RenderSliverMultiBoxAdaptor;
impl<W: SliverMultiBoxAdaptorWidget> IntoWidget<SliverMultiBoxAdaptorKind> for W
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
RenderObjectWidget::debug_check_constructor(&self);
}
Rc::new(SliverMultiBoxAdaptor(self, CreationLocation::of_caller()))
}
}
impl<W: SliverMultiBoxAdaptorWidget> Widget for SliverMultiBoxAdaptor<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn key(&self) -> Option<&KeyRef> {
RenderObjectWidget::key(&self.0)
}
fn creation_location(&self) -> Option<&'static Location<'static>> {
self.1.location()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
SliverMultiBoxAdaptorWidget::create_element(&self.0, app, this)
}
fn as_any(&self) -> &dyn Any {
&self.0
}
fn widget_type(&self) -> TypeId {
TypeId::of::<W>()
}
fn type_name(&self) -> &'static str {
short_type_name::<W>()
}
fn kind(&self) -> WidgetKind {
WidgetKind::Other
}
fn to_string_short(&self) -> String {
RenderObjectWidget::to_string_short(&self.0)
}
fn debug_fill_properties(&self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
RenderObjectWidget::debug_fill_properties(&self.0, app, properties);
}
}
impl<W: SliverMultiBoxAdaptorWidget> Debug for SliverMultiBoxAdaptor<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Debug)]
pub struct SliverList {
pub key: Option<KeyRef>,
pub delegate: SliverChildDelegateRef,
}
impl SliverList {
pub fn new(delegate: SliverChildDelegateRef) -> SliverList {
SliverList {
key: None,
delegate,
}
}
pub fn builder(
item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
) -> SliverListBuilder {
SliverListBuilder::new(Rc::new(item_builder))
}
pub fn separated(
item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
separator_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
) -> SliverListSeparated {
SliverListSeparated::new(Rc::new(item_builder), Rc::new(separator_builder))
}
pub fn list(children: Vec<WidgetRef>) -> SliverListList {
SliverListList::new(children)
}
pub fn key(mut self, key: KeyRef) -> SliverList {
self.key = Some(key);
self
}
}
impl RenderObjectWidget for SliverList {
type RenderObject = RenderSliverList;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
}
fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
RenderSliverList::new(app, child_manager_of::<SliverList>(app, context)).as_object()
}
}
impl SliverWithKeepAliveWidget for SliverList {}
impl SliverMultiBoxAdaptorWidget for SliverList {
fn delegate(&self) -> &SliverChildDelegateRef {
&self.delegate
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
SliverMultiBoxAdaptorElement::<SliverList>::new(app, this, true).as_element()
}
}
pub struct SliverListBuilder {
key: Option<KeyRef>,
delegate: SliverChildBuilderDelegate,
}
macro_rules! builder_constructor_setters {
($name:ident) => {
pub fn key(mut self, key: KeyRef) -> $name {
self.key = Some(key);
self
}
pub fn item_count(mut self, item_count: i32) -> $name {
self.delegate = self.delegate.child_count(item_count);
self
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
self.delegate = self.delegate.add_automatic_keep_alives(value);
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
self.delegate = self.delegate.add_repaint_boundaries(value);
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> $name {
self.delegate = self.delegate.add_semantic_indexes(value);
self
}
};
}
macro_rules! list_constructor_setters {
($name:ident) => {
pub fn key(mut self, key: KeyRef) -> $name {
self.key = Some(key);
self
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
self.delegate = self.delegate.add_automatic_keep_alives(value);
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
self.delegate = self.delegate.add_repaint_boundaries(value);
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> $name {
self.delegate = self.delegate.add_semantic_indexes(value);
self
}
};
}
pub(crate) use builder_constructor_setters;
pub(crate) use list_constructor_setters;
impl SliverListBuilder {
fn new(item_builder: NullableIndexedWidgetBuilder) -> SliverListBuilder {
SliverListBuilder {
key: None,
delegate: SliverChildBuilderDelegate::from_builder(item_builder),
}
}
builder_constructor_setters!(SliverListBuilder);
pub fn semantic_index_offset(mut self, value: i32) -> SliverListBuilder {
self.delegate = self.delegate.semantic_index_offset(value);
self
}
pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> SliverListBuilder {
self.delegate = self.delegate.find_child_index_callback(value);
self
}
pub fn build(self) -> SliverList {
let mut list = SliverList::new(self.delegate.into_delegate());
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverListBuilder {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverListSeparated {
key: Option<KeyRef>,
item_builder: NullableIndexedWidgetBuilder,
separator_builder: NullableIndexedWidgetBuilder,
item_count: Option<i32>,
find_item_index_callback: Option<ChildIndexGetter>,
find_child_index_callback: Option<ChildIndexGetter>,
add_automatic_keep_alives: bool,
add_repaint_boundaries: bool,
add_semantic_indexes: bool,
}
impl SliverListSeparated {
fn new(
item_builder: NullableIndexedWidgetBuilder,
separator_builder: NullableIndexedWidgetBuilder,
) -> SliverListSeparated {
SliverListSeparated {
key: None,
item_builder,
separator_builder,
item_count: None,
find_item_index_callback: None,
find_child_index_callback: None,
add_automatic_keep_alives: true,
add_repaint_boundaries: true,
add_semantic_indexes: true,
}
}
pub fn key(mut self, key: KeyRef) -> SliverListSeparated {
self.key = Some(key);
self
}
pub fn item_count(mut self, item_count: i32) -> SliverListSeparated {
self.item_count = Some(item_count);
self
}
pub fn find_item_index_callback(mut self, value: ChildIndexGetter) -> SliverListSeparated {
debug_assert!(
self.find_child_index_callback.is_none(),
"Cannot provide both findItemIndexCallback and findChildIndexCallback. Use \
findItemIndexCallback as findChildIndexCallback is deprecated."
);
self.find_item_index_callback = Some(value);
self
}
#[deprecated(
note = "Use find_item_index_callback instead. find_child_index_callback returns child \
indices (which include separators), while find_item_index_callback returns item \
indices (which do not)."
)]
pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> SliverListSeparated {
debug_assert!(
self.find_item_index_callback.is_none(),
"Cannot provide both findItemIndexCallback and findChildIndexCallback. Use \
findItemIndexCallback as findChildIndexCallback is deprecated."
);
self.find_child_index_callback = Some(value);
self
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverListSeparated {
self.add_automatic_keep_alives = value;
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> SliverListSeparated {
self.add_repaint_boundaries = value;
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> SliverListSeparated {
self.add_semantic_indexes = value;
self
}
pub fn build(self) -> SliverList {
let (item_builder, separator_builder) = (self.item_builder, self.separator_builder);
let builder: NullableIndexedWidgetBuilder =
Rc::new(move |app: &mut App, context: BuildContext, index: i32| {
let item_index = index / 2;
if index % 2 == 0 {
item_builder(app, context, item_index)
} else {
let widget = separator_builder(app, context, item_index);
debug_assert!(widget.is_some(), "separator_builder cannot return None.");
widget
}
});
let semantic_index_callback: SemanticIndexCallback = Rc::new(|_widget, index| {
if index % 2 == 0 {
Some(index / 2)
} else {
None
}
});
let mut delegate = SliverChildBuilderDelegate::from_builder(builder)
.add_automatic_keep_alives(self.add_automatic_keep_alives)
.add_repaint_boundaries(self.add_repaint_boundaries)
.add_semantic_indexes(self.add_semantic_indexes)
.semantic_index_callback(semantic_index_callback);
if let Some(item_count) = self.item_count {
delegate = delegate.child_count(0.max(item_count * 2 - 1));
}
match (
self.find_item_index_callback,
self.find_child_index_callback,
) {
(Some(find_item_index_callback), _) => {
delegate = delegate.find_child_index_callback(Rc::new(move |key| {
find_item_index_callback(key).map(|item_index| item_index * 2)
}));
}
(None, Some(find_child_index_callback)) => {
delegate = delegate.find_child_index_callback(find_child_index_callback);
}
(None, None) => {}
}
let mut list = SliverList::new(delegate.into_delegate());
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverListSeparated {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverListList {
key: Option<KeyRef>,
delegate: SliverChildListDelegate,
}
impl SliverListList {
fn new(children: Vec<WidgetRef>) -> SliverListList {
SliverListList {
key: None,
delegate: SliverChildListDelegate::new(children),
}
}
list_constructor_setters!(SliverListList);
pub fn build(self) -> SliverList {
let mut list = SliverList::new(self.delegate.into_delegate());
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverListList {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
#[derive(Debug)]
pub struct SliverFixedExtentList {
pub key: Option<KeyRef>,
pub delegate: SliverChildDelegateRef,
pub item_extent: f64,
}
impl SliverFixedExtentList {
pub fn new(delegate: SliverChildDelegateRef, item_extent: f64) -> SliverFixedExtentList {
SliverFixedExtentList {
key: None,
delegate,
item_extent,
}
}
pub fn builder(
item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
item_extent: f64,
) -> SliverFixedExtentListBuilder {
SliverFixedExtentListBuilder::new(Rc::new(item_builder), item_extent)
}
pub fn list(children: Vec<WidgetRef>, item_extent: f64) -> SliverFixedExtentListList {
SliverFixedExtentListList::new(children, item_extent)
}
pub fn key(mut self, key: KeyRef) -> SliverFixedExtentList {
self.key = Some(key);
self
}
}
impl RenderObjectWidget for SliverFixedExtentList {
type RenderObject = RenderSliverFixedExtentList;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
}
fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
RenderSliverFixedExtentList::new(
app,
child_manager_of::<SliverFixedExtentList>(app, context),
self.item_extent,
)
.as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderSliverFixedExtentList>,
) {
render_object.set_item_extent(app, self.item_extent);
}
}
impl SliverWithKeepAliveWidget for SliverFixedExtentList {}
impl SliverMultiBoxAdaptorWidget for SliverFixedExtentList {
fn delegate(&self) -> &SliverChildDelegateRef {
&self.delegate
}
}
pub struct SliverFixedExtentListBuilder {
key: Option<KeyRef>,
delegate: SliverChildBuilderDelegate,
item_extent: f64,
}
impl SliverFixedExtentListBuilder {
fn new(
item_builder: NullableIndexedWidgetBuilder,
item_extent: f64,
) -> SliverFixedExtentListBuilder {
SliverFixedExtentListBuilder {
key: None,
delegate: SliverChildBuilderDelegate::from_builder(item_builder),
item_extent,
}
}
builder_constructor_setters!(SliverFixedExtentListBuilder);
pub fn semantic_index_offset(mut self, value: i32) -> SliverFixedExtentListBuilder {
self.delegate = self.delegate.semantic_index_offset(value);
self
}
pub fn find_child_index_callback(
mut self,
value: ChildIndexGetter,
) -> SliverFixedExtentListBuilder {
self.delegate = self.delegate.find_child_index_callback(value);
self
}
pub fn build(self) -> SliverFixedExtentList {
let mut list = SliverFixedExtentList::new(self.delegate.into_delegate(), self.item_extent);
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverFixedExtentListBuilder {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverFixedExtentListList {
key: Option<KeyRef>,
delegate: SliverChildListDelegate,
item_extent: f64,
}
impl SliverFixedExtentListList {
fn new(children: Vec<WidgetRef>, item_extent: f64) -> SliverFixedExtentListList {
SliverFixedExtentListList {
key: None,
delegate: SliverChildListDelegate::new(children),
item_extent,
}
}
list_constructor_setters!(SliverFixedExtentListList);
pub fn build(self) -> SliverFixedExtentList {
let mut list = SliverFixedExtentList::new(self.delegate.into_delegate(), self.item_extent);
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverFixedExtentListList {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverVariedExtentList {
pub key: Option<KeyRef>,
pub delegate: SliverChildDelegateRef,
pub item_extent_builder: ItemExtentBuilder,
}
impl SliverVariedExtentList {
pub fn new(
delegate: SliverChildDelegateRef,
item_extent_builder: ItemExtentBuilder,
) -> SliverVariedExtentList {
SliverVariedExtentList {
key: None,
delegate,
item_extent_builder,
}
}
pub fn builder(
item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
item_extent_builder: ItemExtentBuilder,
) -> SliverVariedExtentListBuilder {
SliverVariedExtentListBuilder::new(Rc::new(item_builder), item_extent_builder)
}
pub fn list(
children: Vec<WidgetRef>,
item_extent_builder: ItemExtentBuilder,
) -> SliverVariedExtentListList {
SliverVariedExtentListList::new(children, item_extent_builder)
}
pub fn key(mut self, key: KeyRef) -> SliverVariedExtentList {
self.key = Some(key);
self
}
}
impl Debug for SliverVariedExtentList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SliverVariedExtentList")
.field("key", &self.key)
.field("delegate", &self.delegate)
.finish_non_exhaustive()
}
}
impl RenderObjectWidget for SliverVariedExtentList {
type RenderObject = RenderSliverVariedExtentList;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
}
fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
RenderSliverVariedExtentList::new(
app,
child_manager_of::<SliverVariedExtentList>(app, context),
Rc::clone(&self.item_extent_builder),
)
.as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderSliverVariedExtentList>,
) {
render_object.set_item_extent_builder(app, Rc::clone(&self.item_extent_builder));
}
}
impl SliverWithKeepAliveWidget for SliverVariedExtentList {}
impl SliverMultiBoxAdaptorWidget for SliverVariedExtentList {
fn delegate(&self) -> &SliverChildDelegateRef {
&self.delegate
}
}
pub struct SliverVariedExtentListBuilder {
key: Option<KeyRef>,
delegate: SliverChildBuilderDelegate,
item_extent_builder: ItemExtentBuilder,
}
impl SliverVariedExtentListBuilder {
fn new(
item_builder: NullableIndexedWidgetBuilder,
item_extent_builder: ItemExtentBuilder,
) -> SliverVariedExtentListBuilder {
SliverVariedExtentListBuilder {
key: None,
delegate: SliverChildBuilderDelegate::from_builder(item_builder),
item_extent_builder,
}
}
builder_constructor_setters!(SliverVariedExtentListBuilder);
pub fn find_child_index_callback(
mut self,
value: ChildIndexGetter,
) -> SliverVariedExtentListBuilder {
self.delegate = self.delegate.find_child_index_callback(value);
self
}
pub fn build(self) -> SliverVariedExtentList {
let mut list =
SliverVariedExtentList::new(self.delegate.into_delegate(), self.item_extent_builder);
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverVariedExtentListBuilder {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverVariedExtentListList {
key: Option<KeyRef>,
delegate: SliverChildListDelegate,
item_extent_builder: ItemExtentBuilder,
}
impl SliverVariedExtentListList {
fn new(
children: Vec<WidgetRef>,
item_extent_builder: ItemExtentBuilder,
) -> SliverVariedExtentListList {
SliverVariedExtentListList {
key: None,
delegate: SliverChildListDelegate::new(children),
item_extent_builder,
}
}
list_constructor_setters!(SliverVariedExtentListList);
pub fn build(self) -> SliverVariedExtentList {
let mut list =
SliverVariedExtentList::new(self.delegate.into_delegate(), self.item_extent_builder);
if let Some(key) = self.key {
list = list.key(key);
}
list
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverVariedExtentListList {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
#[derive(Debug)]
pub struct SliverGrid {
pub key: Option<KeyRef>,
pub delegate: SliverChildDelegateRef,
pub grid_delegate: Rc<dyn SliverGridDelegate>,
}
impl SliverGrid {
pub fn new(
delegate: SliverChildDelegateRef,
grid_delegate: Rc<dyn SliverGridDelegate>,
) -> SliverGrid {
SliverGrid {
key: None,
delegate,
grid_delegate,
}
}
pub fn builder(
grid_delegate: Rc<dyn SliverGridDelegate>,
item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
) -> SliverGridBuilder {
SliverGridBuilder::new(grid_delegate, Rc::new(item_builder))
}
pub fn count(cross_axis_count: i32) -> SliverGridCount {
SliverGridCount {
key: None,
grid_delegate: SliverGridDelegateWithFixedCrossAxisCount::new(cross_axis_count),
children: Vec::new(),
}
}
pub fn extent(max_cross_axis_extent: f64) -> SliverGridExtent {
SliverGridExtent {
key: None,
grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent::new(max_cross_axis_extent),
children: Vec::new(),
}
}
pub fn list(
grid_delegate: Rc<dyn SliverGridDelegate>,
children: Vec<WidgetRef>,
) -> SliverGridList {
SliverGridList {
key: None,
delegate: SliverChildListDelegate::new(children),
grid_delegate,
}
}
pub fn key(mut self, key: KeyRef) -> SliverGrid {
self.key = Some(key);
self
}
fn keyed(self, key: Option<KeyRef>) -> SliverGrid {
match key {
Some(key) => self.key(key),
None => self,
}
}
}
impl RenderObjectWidget for SliverGrid {
type RenderObject = RenderSliverGrid;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
SliverMultiBoxAdaptorWidget::debug_fill_properties(self, properties);
}
fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
RenderSliverGrid::new(
app,
child_manager_of::<SliverGrid>(app, context),
Rc::clone(&self.grid_delegate),
)
.as_object()
}
fn update_render_object(
&self,
app: &mut App,
_context: BuildContext,
render_object: RenderHandle<RenderSliverGrid>,
) {
render_object.set_grid_delegate(app, Rc::clone(&self.grid_delegate));
}
}
impl SliverWithKeepAliveWidget for SliverGrid {}
impl SliverMultiBoxAdaptorWidget for SliverGrid {
fn delegate(&self) -> &SliverChildDelegateRef {
&self.delegate
}
fn estimate_max_scroll_offset(
&self,
constraints: Option<SliverConstraints>,
first_index: i32,
last_index: i32,
leading_scroll_offset: f64,
trailing_scroll_offset: f64,
) -> Option<f64> {
debug_assert!(last_index >= first_index);
self.delegate
.estimate_max_scroll_offset(
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
)
.or_else(|| {
let constraints = constraints.expect("a grid estimates during its layout");
let child_count = self
.delegate
.estimated_child_count()
.expect("a grid whose delegate cannot estimate counts its children");
Some(
self.grid_delegate
.get_layout(constraints)
.compute_max_scroll_offset(child_count),
)
})
}
}
pub struct SliverGridBuilder {
key: Option<KeyRef>,
delegate: SliverChildBuilderDelegate,
grid_delegate: Rc<dyn SliverGridDelegate>,
}
impl SliverGridBuilder {
fn new(
grid_delegate: Rc<dyn SliverGridDelegate>,
item_builder: NullableIndexedWidgetBuilder,
) -> SliverGridBuilder {
SliverGridBuilder {
key: None,
delegate: SliverChildBuilderDelegate::from_builder(item_builder),
grid_delegate,
}
}
builder_constructor_setters!(SliverGridBuilder);
pub fn semantic_index_offset(mut self, value: i32) -> SliverGridBuilder {
self.delegate = self.delegate.semantic_index_offset(value);
self
}
pub fn find_child_index_callback(mut self, value: ChildIndexGetter) -> SliverGridBuilder {
self.delegate = self.delegate.find_child_index_callback(value);
self
}
pub fn build(self) -> SliverGrid {
SliverGrid::new(self.delegate.into_delegate(), self.grid_delegate).keyed(self.key)
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridBuilder {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
macro_rules! tiles_constructor_setters {
($name:ident) => {
pub fn key(mut self, key: KeyRef) -> $name {
self.key = Some(key);
self
}
pub fn main_axis_spacing(mut self, value: f64) -> $name {
self.grid_delegate = self.grid_delegate.main_axis_spacing(value);
self
}
pub fn cross_axis_spacing(mut self, value: f64) -> $name {
self.grid_delegate = self.grid_delegate.cross_axis_spacing(value);
self
}
pub fn child_aspect_ratio(mut self, value: f64) -> $name {
self.grid_delegate = self.grid_delegate.child_aspect_ratio(value);
self
}
pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
self.children = children.into_iter().collect();
self
}
pub fn build(self) -> SliverGrid {
SliverGrid::new(
SliverChildListDelegate::new(self.children).into_delegate(),
Rc::new(self.grid_delegate),
)
.keyed(self.key)
}
};
}
pub struct SliverGridCount {
key: Option<KeyRef>,
grid_delegate: SliverGridDelegateWithFixedCrossAxisCount,
children: Vec<WidgetRef>,
}
impl SliverGridCount {
tiles_constructor_setters!(SliverGridCount);
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridCount {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverGridExtent {
key: Option<KeyRef>,
grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent,
children: Vec<WidgetRef>,
}
impl SliverGridExtent {
tiles_constructor_setters!(SliverGridExtent);
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridExtent {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub struct SliverGridList {
key: Option<KeyRef>,
delegate: SliverChildListDelegate,
grid_delegate: Rc<dyn SliverGridDelegate>,
}
impl SliverGridList {
list_constructor_setters!(SliverGridList);
pub fn semantic_index_offset(mut self, value: i32) -> SliverGridList {
self.delegate = self.delegate.semantic_index_offset(value);
self
}
pub fn build(self) -> SliverGrid {
SliverGrid::new(self.delegate.into_delegate(), self.grid_delegate).keyed(self.key)
}
}
impl IntoWidget<SliverMultiBoxAdaptorKind> for SliverGridList {
#[cfg_attr(debug_assertions, track_caller)]
fn into_widget(self) -> WidgetRef {
self.build().into_widget()
}
}
pub fn child_manager_of<W: SliverMultiBoxAdaptorWidget>(
app: &App,
context: BuildContext,
) -> Rc<dyn RenderSliverBoxChildManager>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
let element = context
.downcast::<SliverMultiBoxAdaptorElement<W>>(app)
.expect("a SliverMultiBoxAdaptorWidget creates its render object from its own element");
element.as_child_manager()
}
pub struct SliverMultiBoxAdaptorElementData {
replace_moved_children: bool,
child_elements: BTreeMap<i32, Option<AnyElement>>,
current_before_child: Option<AnyRenderBox>,
currently_updating_child_index: Option<i32>,
did_underflow: bool,
}
impl SliverMultiBoxAdaptorElementData {
pub fn new(replace_moved_children: bool) -> SliverMultiBoxAdaptorElementData {
SliverMultiBoxAdaptorElementData {
replace_moved_children,
child_elements: BTreeMap::new(),
current_before_child: None,
currently_updating_child_index: None,
did_underflow: false,
}
}
}
pub trait SliverMultiBoxAdaptorElementBase:
RenderObjectElement + RenderObjectElementWidget
where
Self::Widget: SliverMultiBoxAdaptorWidget,
<Self::Widget as RenderObjectWidget>::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn adaptor_data(self: Handle<Self>, app: &App) -> &SliverMultiBoxAdaptorElementData;
fn adaptor_data_mut(self: Handle<Self>, app: &mut App)
-> &mut SliverMultiBoxAdaptorElementData;
fn as_child_manager(self: Handle<Self>) -> Rc<dyn RenderSliverBoxChildManager> {
Rc::new(ChildManager(self))
}
fn build(self: Handle<Self>, app: &mut App, index: i32) -> Option<WidgetRef> {
let delegate = Rc::clone(Self::widget_of(self.as_element().widget(app)).delegate());
delegate.build(app, self.as_element(), index)
}
fn update_child(
self: Handle<Self>,
app: &mut App,
child: Option<AnyElement>,
new_widget: Option<WidgetRef>,
new_slot: Option<Slot>,
) -> Option<AnyElement> {
let old = Self::adaptor_parent_data(app, child)
.map(|object| (object, Self::layout_offset(app, object)));
let new_child = self
.as_element()
.update_child(app, child, new_widget, new_slot);
let new = Self::adaptor_parent_data(app, new_child);
if let Some((old_object, layout_offset)) = old
&& let Some(new_object) = new
&& old_object != new_object
{
Self::set_layout_offset(app, new_object, layout_offset);
}
new_child
}
fn adaptor_parent_data(app: &App, child: Option<AnyElement>) -> Option<AnyRenderObject> {
child
.and_then(|child| child.render_object(app))
.filter(|object| object.parent_data_is::<SliverMultiBoxAdaptorParentData>(app))
}
fn layout_offset(app: &App, object: AnyRenderObject) -> Option<f64> {
object
.parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
.layout_offset()
}
fn set_layout_offset(app: &mut App, object: AnyRenderObject, value: Option<f64>) {
object
.parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
.set_layout_offset(value);
}
fn process_element(
self: Handle<Self>,
app: &mut App,
index: i32,
new_children: &BTreeMap<i32, Option<AnyElement>>,
index_to_layout_offset: &HashMap<i32, f64>,
children_updated: &mut bool,
) {
self.adaptor_data_mut(app).currently_updating_child_index = Some(index);
let existing = self
.adaptor_data(app)
.child_elements
.get(&index)
.copied()
.flatten();
let planned = new_children.get(&index).copied().flatten();
if existing.is_some() && existing != planned {
let deactivated = self.update_child(app, existing, None, Some(Slot::Index(index)));
self.adaptor_data_mut(app)
.child_elements
.insert(index, deactivated);
*children_updated = true;
}
let built = self.build(app, index);
let new_child = self.update_child(app, planned, built, Some(Slot::Index(index)));
match new_child {
Some(new_child) => {
*children_updated = *children_updated
|| self
.adaptor_data(app)
.child_elements
.get(&index)
.copied()
.flatten()
!= Some(new_child);
self.adaptor_data_mut(app)
.child_elements
.insert(index, Some(new_child));
let object = new_child
.render_object(app)
.expect("a built child has a render object");
if index == 0 {
Self::set_layout_offset(app, object, Some(0.0));
} else if let Some(offset) = index_to_layout_offset.get(&index) {
Self::set_layout_offset(app, object, Some(*offset));
}
let parent_data = object.parent_data_of::<SliverMultiBoxAdaptorParentData>(app);
if !parent_data.kept_alive() {
self.adaptor_data_mut(app).current_before_child =
Some(object.as_box().expect("a sliver child is a box"));
}
}
None => {
*children_updated = true;
self.adaptor_data_mut(app).child_elements.remove(&index);
}
}
}
fn extrapolate_max_scroll_offset(
first_index: i32,
last_index: i32,
leading_scroll_offset: f64,
trailing_scroll_offset: f64,
child_count: i32,
) -> f64 {
if last_index == child_count - 1 {
return trailing_scroll_offset;
}
let reified_count = last_index - first_index + 1;
let average_extent =
(trailing_scroll_offset - leading_scroll_offset) / f64::from(reified_count);
let remaining_count = child_count - last_index - 1;
trailing_scroll_offset + average_extent * f64::from(remaining_count)
}
fn in_build_scope(
self: Handle<Self>,
app: &mut App,
callback: impl FnOnce(&mut App) + 'static,
) {
let owner = self
.as_element()
.owner(app)
.expect("a mounted element has an owner");
owner.build_scope(app, self.as_element(), Some(Box::new(callback)));
}
fn create_child(self: Handle<Self>, app: &mut App, index: i32, after: Option<AnyRenderBox>) {
debug_assert!(
self.adaptor_data(app)
.currently_updating_child_index
.is_none()
);
self.in_build_scope(app, move |app| {
let insert_first = after.is_none();
debug_assert!(
insert_first
|| self
.adaptor_data(app)
.child_elements
.get(&(index - 1))
.copied()
.flatten()
.is_some()
);
let before = if insert_first {
None
} else {
self.adaptor_data(app).child_elements[&(index - 1)]
.expect("asserted above")
.render_object(app)
.map(|object| object.as_box().expect("a sliver child is a box"))
};
self.adaptor_data_mut(app).current_before_child = before;
self.adaptor_data_mut(app).currently_updating_child_index = Some(index);
let built = self.build(app, index);
let existing = self
.adaptor_data(app)
.child_elements
.get(&index)
.copied()
.flatten();
let new_child = self.update_child(app, existing, built, Some(Slot::Index(index)));
self.adaptor_data_mut(app).currently_updating_child_index = None;
match new_child {
Some(new_child) => {
self.adaptor_data_mut(app)
.child_elements
.insert(index, Some(new_child));
}
None => {
self.adaptor_data_mut(app).child_elements.remove(&index);
}
}
});
}
fn remove_child(self: Handle<Self>, app: &mut App, child: AnyRenderBox) {
let index = self.typed_render_object(app).index_of(app, child);
debug_assert!(
self.adaptor_data(app)
.currently_updating_child_index
.is_none()
);
debug_assert!(index >= 0);
self.in_build_scope(app, move |app| {
debug_assert!(self.adaptor_data(app).child_elements.contains_key(&index));
self.adaptor_data_mut(app).currently_updating_child_index = Some(index);
let existing = self
.adaptor_data(app)
.child_elements
.get(&index)
.copied()
.flatten();
let result = self.update_child(app, existing, None, Some(Slot::Index(index)));
debug_assert!(result.is_none());
self.adaptor_data_mut(app).currently_updating_child_index = None;
self.adaptor_data_mut(app).child_elements.remove(&index);
debug_assert!(!self.adaptor_data(app).child_elements.contains_key(&index));
});
}
fn estimate_max_scroll_offset(
self: Handle<Self>,
app: &App,
constraints: SliverConstraints,
first_index: Option<i32>,
last_index: Option<i32>,
leading_scroll_offset: Option<f64>,
trailing_scroll_offset: Option<f64>,
) -> f64 {
let Some(child_count) = self.estimated_child_count(app) else {
return f64::INFINITY;
};
let first_index = first_index.expect("a finite child list reports its window");
let last_index = last_index.expect("a finite child list reports its window");
let leading_scroll_offset =
leading_scroll_offset.expect("a finite child list reports its window");
let trailing_scroll_offset =
trailing_scroll_offset.expect("a finite child list reports its window");
Self::widget_of(self.as_element().widget(app))
.estimate_max_scroll_offset(
Some(constraints),
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
)
.unwrap_or_else(|| {
Self::extrapolate_max_scroll_offset(
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
child_count,
)
})
}
fn estimated_child_count(self: Handle<Self>, app: &App) -> Option<i32> {
Self::widget_of(self.as_element().widget(app))
.delegate()
.estimated_child_count()
}
fn child_count(self: Handle<Self>, app: &mut App) -> i32 {
if let Some(result) = self.estimated_child_count(app) {
return result;
}
let mut lo = 0;
let mut hi = 1;
let max = i32::MAX;
while self.build(app, hi - 1).is_some() {
lo = hi - 1;
if hi < max / 2 {
hi *= 2;
} else if hi < max {
hi = max;
} else {
panic!(
"Could not find the number of children in {:?}.\nThe child_count getter was \
called (implying that the delegate's builder returned None for a positive \
index), but even building the child with index {hi} (the maximum possible \
integer) did not return None. Consider implementing estimated_child_count to \
avoid the cost of searching for the final child.",
Self::widget_of(self.as_element().widget(app)).delegate()
);
}
}
while hi - lo > 1 {
let mid = (hi - lo) / 2 + lo;
if self.build(app, mid - 1).is_none() {
hi = mid;
} else {
lo = mid;
}
}
lo
}
fn did_start_layout(self: Handle<Self>, app: &App) {
debug_assert!(self.debug_assert_child_list_locked(app));
}
fn did_finish_layout(self: Handle<Self>, app: &App) {
debug_assert!(self.debug_assert_child_list_locked(app));
let first_index = self
.adaptor_data(app)
.child_elements
.keys()
.next()
.copied()
.unwrap_or(0);
let last_index = self
.adaptor_data(app)
.child_elements
.keys()
.next_back()
.copied()
.unwrap_or(0);
Self::widget_of(self.as_element().widget(app))
.delegate()
.did_finish_layout(first_index, last_index);
}
fn debug_assert_child_list_locked(self: Handle<Self>, app: &App) -> bool {
debug_assert!(
self.adaptor_data(app)
.currently_updating_child_index
.is_none()
);
true
}
fn did_adopt_child(self: Handle<Self>, app: &mut App, child: AnyRenderBox) {
debug_assert!(
self.adaptor_data(app)
.currently_updating_child_index
.is_some()
);
let index = self.adaptor_data(app).currently_updating_child_index;
child
.as_object()
.parent_data_of_mut::<SliverMultiBoxAdaptorParentData>(app)
.index = index;
}
fn set_did_underflow(self: Handle<Self>, app: &mut App, value: bool) {
self.adaptor_data_mut(app).did_underflow = value;
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
let old_widget = self.as_element().widget(app).clone();
RenderObjectElement::update(self, app, new_widget.clone());
let new_delegate = Rc::clone(Self::widget_of(&new_widget).delegate());
let old_delegate = Rc::clone(Self::widget_of(&old_widget).delegate());
if !same_delegate(&new_delegate, &old_delegate)
&& (new_delegate.delegate_type() != old_delegate.delegate_type()
|| new_delegate.should_rebuild(&*old_delegate))
{
Element::perform_rebuild(self, app);
}
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
RenderObjectElement::perform_rebuild(self, app);
self.adaptor_data_mut(app).current_before_child = None;
let mut children_updated = false;
debug_assert!(
self.adaptor_data(app)
.currently_updating_child_index
.is_none()
);
let mut new_children: BTreeMap<i32, Option<AnyElement>> = BTreeMap::new();
let mut index_to_layout_offset: HashMap<i32, f64> = HashMap::new();
for index in self
.adaptor_data(app)
.child_elements
.keys()
.copied()
.collect::<Vec<_>>()
{
let child = self.adaptor_data(app).child_elements[&index].expect("a live child");
let key = child.widget(app).key().cloned();
let new_index = key.and_then(|key| {
Self::widget_of(self.as_element().widget(app))
.delegate()
.find_index_by_key(&key)
});
let child_parent_data = Self::adaptor_parent_data(app, Some(child));
if let Some(object) = child_parent_data
&& let Some(layout_offset) = Self::layout_offset(app, object)
{
index_to_layout_offset.insert(index, layout_offset);
}
match new_index {
Some(new_index) if new_index != index => {
if let Some(object) = child_parent_data {
Self::set_layout_offset(app, object, None);
}
new_children.insert(new_index, Some(child));
if self.adaptor_data(app).replace_moved_children {
new_children.entry(index).or_insert(None);
}
self.adaptor_data_mut(app).child_elements.remove(&index);
}
_ => {
new_children.entry(index).or_insert(Some(child));
}
}
}
self.typed_render_object(app)
.set_debug_child_integrity_enabled(app, false);
for index in new_children.keys().copied().collect::<Vec<_>>() {
self.process_element(
app,
index,
&new_children,
&index_to_layout_offset,
&mut children_updated,
);
}
if !children_updated && self.adaptor_data(app).did_underflow {
let last_key = self
.adaptor_data(app)
.child_elements
.keys()
.next_back()
.copied()
.unwrap_or(-1);
let right_boundary = last_key + 1;
let existing = self
.adaptor_data(app)
.child_elements
.get(&right_boundary)
.copied()
.flatten();
new_children.insert(right_boundary, existing);
self.process_element(
app,
right_boundary,
&new_children,
&index_to_layout_offset,
&mut children_updated,
);
}
self.adaptor_data_mut(app).currently_updating_child_index = None;
self.typed_render_object(app)
.set_debug_child_integrity_enabled(app, true);
}
fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
let slot = child.slot(app).expect("a lazily built child has an index");
let Slot::Index(index) = slot else {
unreachable!("a lazily built child has an index slot");
};
debug_assert!(self.adaptor_data(app).child_elements.contains_key(&index));
self.adaptor_data_mut(app).child_elements.remove(&index);
}
fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
let children: Vec<AnyElement> = self
.adaptor_data(app)
.child_elements
.values()
.map(|child| child.expect("no child slot is empty outside a rebuild"))
.collect();
for child in children {
visitor(child);
}
}
fn debug_visit_onstage_children(
self: Handle<Self>,
app: &App,
visitor: &mut dyn FnMut(AnyElement),
) {
let Some(sliver) = self
.as_element()
.render_object(app)
.and_then(|render| render.as_sliver())
else {
return;
};
let constraints = sliver.constraints(app);
let children: Vec<AnyElement> = self
.adaptor_data(app)
.child_elements
.values()
.map(|child| child.expect("no child slot is empty outside a rebuild"))
.collect();
for child in children {
let Some(render) = child.render_object(app) else {
continue;
};
let paint_bounds = render.paint_bounds(app);
let item_extent = match constraints.axis() {
waft_painting::Axis::Horizontal => paint_bounds.width(),
waft_painting::Axis::Vertical => paint_bounds.height(),
};
let onstage = render
.parent_data(app)
.and_then(|data| data.part::<waft_rendering::SliverMultiBoxAdaptorParentData>())
.and_then(|data| data.layout_offset())
.is_some_and(|layout_offset| {
layout_offset < constraints.scroll_offset + constraints.remaining_paint_extent
&& layout_offset + item_extent > constraints.scroll_offset
});
if onstage {
visitor(child);
}
}
}
fn insert_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
debug_assert!(
slot == self
.adaptor_data(app)
.currently_updating_child_index
.map(Slot::Index)
);
let render_object = self.typed_render_object(app);
let before = self.adaptor_data(app).current_before_child;
let child = child.as_box().expect("a sliver child is a box");
RenderSliverMultiBoxAdaptor::insert(render_object, app, child, before);
debug_assert!(
slot == child
.as_object()
.parent_data_of::<SliverMultiBoxAdaptorParentData>(app)
.index
.map(Slot::Index)
);
}
fn move_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
_old_slot: Option<Slot>,
new_slot: Option<Slot>,
) {
debug_assert!(
new_slot
== self
.adaptor_data(app)
.currently_updating_child_index
.map(Slot::Index)
);
let render_object = self.typed_render_object(app);
let before = self.adaptor_data(app).current_before_child;
let child = child.as_box().expect("a sliver child is a box");
RenderSliverMultiBoxAdaptor::move_child(render_object, app, child, before);
}
fn remove_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
_slot: Option<Slot>,
) {
debug_assert!(
self.adaptor_data(app)
.currently_updating_child_index
.is_some()
);
let render_object = self.typed_render_object(app);
let child = child.as_box().expect("a sliver child is a box");
RenderSliverMultiBoxAdaptor::remove(render_object, app, child);
}
}
struct ChildManager<E: SliverMultiBoxAdaptorElementBase>(Handle<E>)
where
E::Widget: SliverMultiBoxAdaptorWidget,
<E::Widget as RenderObjectWidget>::RenderObject: RenderSliverMultiBoxAdaptor;
impl<E: SliverMultiBoxAdaptorElementBase> RenderSliverBoxChildManager for ChildManager<E>
where
E::Widget: SliverMultiBoxAdaptorWidget,
<E::Widget as RenderObjectWidget>::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn create_child(&self, app: &mut App, index: i32, after: Option<AnyRenderBox>) {
self.0.create_child(app, index, after);
}
fn remove_child(&self, app: &mut App, child: AnyRenderBox) {
self.0.remove_child(app, child);
}
fn estimate_max_scroll_offset(
&self,
app: &App,
constraints: SliverConstraints,
first_index: Option<i32>,
last_index: Option<i32>,
leading_scroll_offset: Option<f64>,
trailing_scroll_offset: Option<f64>,
) -> f64 {
self.0.estimate_max_scroll_offset(
app,
constraints,
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
)
}
fn child_count(&self, app: &mut App) -> i32 {
self.0.child_count(app)
}
fn estimated_child_count(&self, app: &App) -> Option<i32> {
self.0.estimated_child_count(app)
}
fn did_adopt_child(&self, app: &mut App, child: AnyRenderBox) {
self.0.did_adopt_child(app, child);
}
fn set_did_underflow(&self, app: &mut App, value: bool) {
self.0.set_did_underflow(app, value);
}
fn did_start_layout(&self, app: &mut App) {
self.0.did_start_layout(app);
}
fn did_finish_layout(&self, app: &mut App) {
self.0.did_finish_layout(app);
}
fn debug_assert_child_list_locked(&self, app: &App) -> bool {
self.0.debug_assert_child_list_locked(app)
}
}
pub struct SliverMultiBoxAdaptorElement<W: SliverMultiBoxAdaptorWidget>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
element: ElementData,
render_object_element: RenderObjectElementData,
adaptor: SliverMultiBoxAdaptorElementData,
marker: std::marker::PhantomData<fn() -> W>,
}
impl<W: SliverMultiBoxAdaptorWidget> SliverMultiBoxAdaptorElement<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
pub fn new(
app: &mut App,
widget: WidgetRef,
replace_moved_children: bool,
) -> Handle<SliverMultiBoxAdaptorElement<W>> {
debug_assert!(downcast_widget::<W>(&*widget).is_some());
app.create(SliverMultiBoxAdaptorElement::<W> {
element: ElementData::new(widget),
render_object_element: RenderObjectElementData::default(),
adaptor: SliverMultiBoxAdaptorElementData::new(replace_moved_children),
marker: std::marker::PhantomData,
})
.into_tree_node(app)
}
pub fn render_object(self: Handle<Self>, app: &App) -> RenderHandle<W::RenderObject> {
self.typed_render_object(app)
}
}
impl<W: SliverMultiBoxAdaptorWidget> SliverMultiBoxAdaptorElementBase
for SliverMultiBoxAdaptorElement<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn adaptor_data(self: Handle<Self>, app: &App) -> &SliverMultiBoxAdaptorElementData {
&app.get(self).adaptor
}
fn adaptor_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut SliverMultiBoxAdaptorElementData {
&mut app.get_mut(self).adaptor
}
}
impl<W: SliverMultiBoxAdaptorWidget> RenderObjectElementWidget for SliverMultiBoxAdaptorElement<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
type Widget = W;
fn widget_of(widget: &WidgetRef) -> &W {
downcast_widget::<W>(&**widget)
.expect("a SliverMultiBoxAdaptorElement holds its SliverMultiBoxAdaptorWidget")
}
}
impl<W: SliverMultiBoxAdaptorWidget> RenderObjectElement for SliverMultiBoxAdaptorElement<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
&app.get(self).render_object_element
}
fn render_object_element_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut RenderObjectElementData {
&mut app.get_mut(self).render_object_element
}
}
impl<W: SliverMultiBoxAdaptorWidget> Element for SliverMultiBoxAdaptorElement<W>
where
W::RenderObject: RenderSliverMultiBoxAdaptor,
{
crate::element_accessors!();
const IS_RENDER_OBJECT_ELEMENT: bool = true;
fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
self.render_object_element_data(app).render_object()
}
fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
None
}
fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
self.render_object_element_data(app).debug_doing_build()
}
fn mount(
self: Handle<Self>,
app: &mut App,
parent: Option<AnyElement>,
new_slot: Option<Slot>,
) {
RenderObjectElement::mount(self, app, parent, new_slot);
}
fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
SliverMultiBoxAdaptorElementBase::update(self, app, new_widget);
}
fn perform_rebuild(self: Handle<Self>, app: &mut App) {
SliverMultiBoxAdaptorElementBase::perform_rebuild(self, app);
}
fn deactivate(self: Handle<Self>, app: &mut App) {
RenderObjectElement::deactivate(self, app);
}
fn unmount(self: Handle<Self>, app: &mut App) {
RenderObjectElement::unmount(self, app);
}
fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
RenderObjectElement::update_parent_data(self, app, parent_data_element);
}
fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
RenderObjectElement::update_slot(self, app, new_slot);
}
fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
RenderObjectElement::attach_render_object(self, app, new_slot);
}
fn detach_render_object(self: Handle<Self>, app: &mut App) {
RenderObjectElement::detach_render_object(self, app);
}
fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
SliverMultiBoxAdaptorElementBase::forget_child(self, app, child);
}
fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
SliverMultiBoxAdaptorElementBase::visit_children(self, app, visitor);
}
fn debug_visit_onstage_children(
self: Handle<Self>,
app: &App,
visitor: &mut dyn FnMut(AnyElement),
) {
SliverMultiBoxAdaptorElementBase::debug_visit_onstage_children(self, app, visitor);
}
fn insert_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
SliverMultiBoxAdaptorElementBase::insert_render_object_child(self, app, child, slot);
}
fn move_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
old_slot: Option<Slot>,
new_slot: Option<Slot>,
) {
SliverMultiBoxAdaptorElementBase::move_render_object_child(
self, app, child, old_slot, new_slot,
);
}
fn remove_render_object_child(
self: Handle<Self>,
app: &mut App,
child: AnyRenderObject,
slot: Option<Slot>,
) {
SliverMultiBoxAdaptorElementBase::remove_render_object_child(self, app, child, slot);
}
}
#[derive(Debug)]
pub struct KeepAlive {
pub key: Option<KeyRef>,
pub keep_alive: bool,
pub child: WidgetRef,
}
impl KeepAlive {
#[cfg_attr(debug_assertions, track_caller)]
pub fn new<K>(keep_alive: bool, child: impl IntoWidget<K>) -> KeepAlive {
KeepAlive {
key: None,
keep_alive,
child: child.into_widget(),
}
}
pub fn key(mut self, key: KeyRef) -> KeepAlive {
self.key = Some(key);
self
}
}
impl ParentDataWidget for KeepAlive {
type ParentData = SliverMultiBoxAdaptorParentData;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
properties.add(DiagnosticsProperty::new("keepAlive", self.keep_alive));
}
fn child(&self) -> &WidgetRef {
&self.child
}
fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject) {
let parent_data = render_object
.parent_data_mut(app)
.and_then(|parent_data| parent_data.part_mut::<KeepAliveParentData>())
.expect("parent data does not embed a KeepAliveParentData");
if parent_data.keep_alive != self.keep_alive {
parent_data.keep_alive = self.keep_alive;
if !self.keep_alive
&& let Some(parent) = render_object.parent(app)
{
parent.mark_needs_layout(app);
}
}
}
fn debug_can_apply_out_of_turn(&self) -> bool {
self.keep_alive
}
}
#[cfg(test)]
mod tests {
use waft_embedder::TextDirection;
use waft_foundation::AppCell;
use waft_foundation::Ref;
use waft_foundation::ValueKey;
use waft_rendering::{
ContainerRenderObjectMixin, FixedViewportOffset, RenderSliverList, ScrollCacheExtent,
ViewportOffset,
};
use super::*;
use crate::test_harness::Harness;
use crate::widgets::basic::{Directionality, SizedBox};
use crate::widgets::viewport::Viewport;
fn key(value: u32) -> KeyRef {
KeyRef::from(ValueKey::new(value))
}
fn item(value: u32) -> WidgetRef {
SizedBox::new().key(key(value)).height(40.0).into_widget()
}
fn viewport_over(sliver: WidgetRef, offset: &Ref<FixedViewportOffset>) -> WidgetRef {
Directionality::new(
TextDirection::Ltr,
Viewport::new(offset.erase())
.scroll_cache_extent(ScrollCacheExtent::Pixels(0.0))
.slivers(vec![sliver]),
)
.into_widget()
}
fn first_sliver<T: waft_rendering::RenderObject>(
harness: &Harness,
app: &App,
) -> RenderHandle<T> {
harness
.render_root(app)
.child(app)
.expect("a child")
.as_object()
.downcast::<waft_rendering::RenderViewport>(app)
.expect("a RenderViewport")
.first_child(app)
.expect("a sliver")
.as_object()
.downcast::<T>(app)
.expect("the sliver under test")
}
fn children_of<T>(list: RenderHandle<T>, app: &App) -> Vec<AnyRenderBox>
where
T: ContainerRenderObjectMixin<ChildType = AnyRenderBox>,
{
let mut children = Vec::new();
let mut child = list.first_child(app);
while let Some(current) = child {
children.push(current);
child = list.child_after(app, current);
}
children
}
#[test]
fn a_keyed_reorder_keeps_the_child_render_objects() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let offset = FixedViewportOffset::zero(&mut app);
let ordered = |values: [u32; 3]| {
SliverList::list(values.map(item).to_vec())
.add_repaint_boundaries(false)
.into_widget()
};
let harness = Harness::mount(&mut app, viewport_over(ordered([0, 1, 2]), &offset));
harness.pump(&mut app);
let list: RenderHandle<RenderSliverList> = first_sliver(&harness, &app);
let before = children_of(list, &app);
assert_eq!(before.len(), 3);
harness.set_child(&mut app, viewport_over(ordered([2, 0, 1]), &offset));
harness.pump(&mut app);
let after = children_of(list, &app);
assert_eq!(after, vec![before[2], before[0], before[1]]);
}
#[test]
fn keep_alive_holds_a_scrolled_off_child() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let offset = FixedViewportOffset::zero(&mut app);
let mut children: Vec<WidgetRef> = vec![
KeepAlive::new(true, SizedBox::new().key(key(0)).height(40.0))
.key(key(100))
.into_widget(),
];
children.extend((1..8).map(item));
let sliver = SliverList::list(children)
.add_automatic_keep_alives(false)
.add_repaint_boundaries(false)
.add_semantic_indexes(false)
.into_widget();
let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
harness.pump(&mut app);
let list: RenderHandle<RenderSliverList> = first_sliver(&harness, &app);
let kept = children_of(list, &app)[0];
assert!(list.keep_alive_children(&app).is_empty());
offset.correct_by(&mut app, 200.0);
list.parent(&app)
.expect("the viewport")
.mark_needs_layout(&mut app);
harness.pump(&mut app);
assert_eq!(list.keep_alive_children(&app), vec![kept]);
assert!(!children_of(list, &app).contains(&kept));
}
#[test]
fn a_fixed_extent_list_forces_the_item_extent() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let offset = FixedViewportOffset::zero(&mut app);
let sliver = SliverFixedExtentList::builder(
|_app, _context, _index| Some(SizedBox::new().height(10.0).into_widget()),
40.0,
)
.item_count(8)
.into_widget();
let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
harness.pump(&mut app);
let list: RenderHandle<RenderSliverFixedExtentList> = first_sliver(&harness, &app);
let children = children_of(list, &app);
assert_eq!(children.len(), 5);
for child in children {
assert_eq!(child.size(&app).height(), 40.0);
}
assert_eq!(list.geometry(&app).scroll_extent, 320.0);
}
#[test]
fn a_sliver_grid_builds_only_the_rows_in_view() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let offset = FixedViewportOffset::zero(&mut app);
let sliver = SliverGrid::builder(
Rc::new(SliverGridDelegateWithFixedCrossAxisCount::new(3).main_axis_extent(50.0)),
|_app, _context, _index| Some(SizedBox::new().into_widget()),
)
.item_count(30)
.add_repaint_boundaries(false)
.into_widget();
let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
harness.pump(&mut app);
let grid: RenderHandle<RenderSliverGrid> = first_sliver(&harness, &app);
let tiles = children_of(grid, &app);
assert_eq!(tiles.len(), 12);
let width = harness.render_root(&app).size(&app).width() / 3.0;
assert_eq!(tiles[4].size(&app), waft_embedder::Size::new(width, 50.0));
let positions: Vec<(f64, f64)> = tiles[3..6]
.iter()
.map(|tile| {
(
RenderSliver::child_main_axis_position(grid, &app, tile.as_object()),
RenderSliver::child_cross_axis_position(grid, &app, tile.as_object()),
)
})
.collect();
assert_eq!(positions, [(50.0, 0.0), (50.0, width), (50.0, 2.0 * width)]);
assert_eq!(grid.geometry(&app).scroll_extent, 500.0, "ten rows of 50");
}
#[test]
fn keep_alive_holds_a_scrolled_off_grid_tile() {
let cell = AppCell::new();
let mut app = cell.borrow_mut();
let offset = FixedViewportOffset::zero(&mut app);
let mut children: Vec<WidgetRef> = vec![
KeepAlive::new(true, SizedBox::new().key(key(0)))
.key(key(100))
.into_widget(),
];
children.extend((1..40).map(item));
let tiles = SliverGridDelegateWithFixedCrossAxisCount::new(2).child_aspect_ratio(3.0);
let sliver = SliverGrid::list(Rc::new(tiles), children)
.add_automatic_keep_alives(false)
.add_repaint_boundaries(false)
.add_semantic_indexes(false)
.into_widget();
let harness = Harness::mount(&mut app, viewport_over(sliver, &offset));
harness.pump(&mut app);
let grid: RenderHandle<RenderSliverGrid> = first_sliver(&harness, &app);
let kept = children_of(grid, &app)[0];
offset.correct_by(&mut app, 300.0);
grid.parent(&app)
.expect("the viewport")
.mark_needs_layout(&mut app);
harness.pump(&mut app);
assert_eq!(grid.keep_alive_children(&app), vec![kept]);
assert!(!children_of(grid, &app).contains(&kept));
}
}