use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::hash::Hasher;
use std::rc::Rc;
use waft_foundation::{App, Handle, Key, Listener, ValueKey};
use waft_rendering::{AnySelectable, SelectionRegistrar, SelectionRegistrarRef};
use crate::framework::{
BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::automatic_keep_alive::{
AutomaticKeepAlive, AutomaticKeepAliveClientMixin, AutomaticKeepAliveClientMixinData,
};
use crate::widgets::basic::{IndexedSemantics, KeyedSubtree, RepaintBoundary};
use crate::widgets::selection_container::{SelectionContainer, SelectionRegistrarScope};
pub type NullableIndexedWidgetBuilder =
Rc<dyn Fn(&mut App, BuildContext, i32) -> Option<WidgetRef>>;
pub type SemanticIndexCallback = Rc<dyn Fn(&WidgetRef, i32) -> Option<i32>>;
fn default_semantic_index_callback() -> SemanticIndexCallback {
Rc::new(|_widget, local_index| Some(local_index))
}
pub trait SliverChildDelegate: Debug + 'static {
fn build(&self, app: &mut App, context: BuildContext, index: i32) -> Option<WidgetRef>;
fn estimated_child_count(&self) -> Option<i32> {
None
}
fn estimate_max_scroll_offset(
&self,
first_index: i32,
last_index: i32,
leading_scroll_offset: f64,
trailing_scroll_offset: f64,
) -> Option<f64> {
let _ = (
first_index,
last_index,
leading_scroll_offset,
trailing_scroll_offset,
);
None
}
fn did_finish_layout(&self, first_index: i32, last_index: i32) {
let _ = (first_index, last_index);
}
fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool;
fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
let _ = key;
None
}
fn as_any(&self) -> &dyn Any;
fn delegate_type(&self) -> TypeId {
self.as_any().type_id()
}
fn debug_fill_description(&self, description: &mut Vec<String>) {
if let Some(children) = self.estimated_child_count() {
description.push(format!("estimated child count: {children}"));
}
}
}
pub type SliverChildDelegateRef = Rc<dyn SliverChildDelegate>;
pub fn same_delegate(a: &SliverChildDelegateRef, b: &SliverChildDelegateRef) -> bool {
Rc::ptr_eq(a, b)
}
#[derive(Clone, Debug)]
struct SaltedValueKey(ValueKey<KeyRef>);
impl SaltedValueKey {
fn new(value: KeyRef) -> SaltedValueKey {
SaltedValueKey(ValueKey::new(value))
}
}
impl Key for SaltedValueKey {
fn eq_key(&self, other: &dyn Key) -> bool {
(other as &dyn Any)
.downcast_ref::<SaltedValueKey>()
.is_some_and(|other| other.0.value == self.0.value)
}
fn hash_key(&self, mut state: &mut dyn Hasher) {
use std::hash::Hash;
TypeId::of::<SaltedValueKey>().hash(&mut state);
self.0.value.hash(&mut state);
}
}
fn unsalt(key: &KeyRef) -> KeyRef {
match (key.key() as &dyn Any).downcast_ref::<SaltedValueKey>() {
Some(salted) => salted.0.value.clone(),
None => key.clone(),
}
}
struct SelectionKeepAlive {
key: Option<KeyRef>,
child: WidgetRef,
}
impl SelectionKeepAlive {
#[cfg_attr(debug_assertions, track_caller)]
fn new<K>(child: impl IntoWidget<K>) -> SelectionKeepAlive {
SelectionKeepAlive {
key: None,
child: child.into_widget(),
}
}
}
impl Debug for SelectionKeepAlive {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SelectionKeepAlive").finish_non_exhaustive()
}
}
impl StatefulWidget for SelectionKeepAlive {
type State = SelectionKeepAliveState;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> SelectionKeepAliveState {
SelectionKeepAliveState {
state: StateData::new(),
keep_alive: AutomaticKeepAliveClientMixinData::new(),
selectables_with_selections: None,
selectable_attachments: None,
registrar: None,
want_keep_alive: false,
}
}
}
struct SelectionKeepAliveState {
state: StateData<SelectionKeepAlive>,
keep_alive: AutomaticKeepAliveClientMixinData,
selectables_with_selections: Option<HashSet<AnySelectable>>,
selectable_attachments: Option<HashMap<AnySelectable, Listener>>,
registrar: Option<SelectionRegistrarRef>,
want_keep_alive: bool,
}
impl SelectionKeepAliveState {
fn registrar_handle(
self: Handle<Self>,
app: &App,
) -> Option<waft_rendering::AnySelectionRegistrar> {
app.get(self)
.registrar
.as_ref()
.map(|registrar| registrar.handle())
}
fn listens_to(self: Handle<Self>, selectable: AnySelectable) -> Listener {
Listener::new(move |app| {
let add = selectable.value(app).has_selection();
SelectionKeepAliveState::update_selectables_with_selections(self, app, selectable, add);
})
}
fn update_selectables_with_selections(
self: Handle<Self>,
app: &mut App,
selectable: AnySelectable,
add: bool,
) {
let has_selection = selectable.value(app).has_selection();
{
let this = app.get_mut(self);
if add {
debug_assert!(has_selection);
this.selectables_with_selections
.get_or_insert_with(HashSet::new)
.insert(selectable);
} else if let Some(selectables) = &mut this.selectables_with_selections {
selectables.remove(&selectable);
}
}
let want = app
.get(self)
.selectables_with_selections
.as_ref()
.is_some_and(|selectables| !selectables.is_empty());
self.set_want_keep_alive(app, want);
}
fn set_want_keep_alive(self: Handle<Self>, app: &mut App, value: bool) {
if app.get(self).want_keep_alive != value {
app.get_mut(self).want_keep_alive = value;
self.update_keep_alive(app);
}
}
}
impl State for SelectionKeepAliveState {
type Widget = SelectionKeepAlive;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
AutomaticKeepAliveClientMixin::init_state(self, app);
}
fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
let new_registrar = SelectionContainer::maybe_of(app, self.context(app));
let current = self.registrar_handle(app);
let new_handle = new_registrar.as_ref().map(|registrar| registrar.handle());
if current == new_handle {
return;
}
let attachments: Vec<AnySelectable> = app
.get(self)
.selectable_attachments
.as_ref()
.map(|attachments| attachments.keys().copied().collect())
.unwrap_or_default();
if let Some(registrar) = current {
for selectable in &attachments {
registrar.remove(app, *selectable);
}
}
app.get_mut(self).registrar = new_registrar;
if let Some(registrar) = self.registrar_handle(app) {
for selectable in &attachments {
registrar.add(app, *selectable);
}
}
}
fn deactivate(self: Handle<Self>, app: &mut App) {
AutomaticKeepAliveClientMixin::deactivate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
let attachments = app.get_mut(self).selectable_attachments.take();
if let Some(attachments) = attachments {
let registrar = self.registrar_handle(app);
for (selectable, listener) in attachments {
if let Some(registrar) = registrar {
registrar.remove(app, selectable);
}
selectable.remove_listener(app, &listener);
}
}
app.get_mut(self).selectables_with_selections = None;
}
fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
let _ = AutomaticKeepAliveClientMixin::build(self, app);
if self.registrar_handle(app).is_none() {
let child = self.widget(app).child.clone();
return child;
}
let child = self.widget(app).child.clone();
SelectionRegistrarScope::new(self.as_selection_registrar().keep(app), child).into_widget()
}
}
impl AutomaticKeepAliveClientMixin for SelectionKeepAliveState {
fn automatic_keep_alive_client_data(
self: Handle<Self>,
app: &App,
) -> &AutomaticKeepAliveClientMixinData {
&app.get(self).keep_alive
}
fn automatic_keep_alive_client_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut AutomaticKeepAliveClientMixinData {
&mut app.get_mut(self).keep_alive
}
fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
app.get(self).want_keep_alive
}
}
impl SelectionRegistrar for SelectionKeepAliveState {
fn add(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
let attachment = self.listens_to(selectable);
selectable.add_listener(app, attachment.clone());
app.get_mut(self)
.selectable_attachments
.get_or_insert_with(HashMap::new)
.insert(selectable, attachment);
self.registrar_handle(app)
.expect("a sliver child with selectables is under a selection container")
.add(app, selectable);
if selectable.value(app).has_selection() {
self.update_selectables_with_selections(app, selectable, true);
}
}
fn remove(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
let Some(attachments) = app.get_mut(self).selectable_attachments.as_mut() else {
return;
};
let attachment = attachments
.remove(&selectable)
.expect("the selectable was attached");
selectable.remove_listener(app, &attachment);
self.registrar_handle(app)
.expect("a sliver child with selectables is under a selection container")
.remove(app, selectable);
self.update_selectables_with_selections(app, selectable, false);
}
}
fn wrap_child(
child: WidgetRef,
index: i32,
add_automatic_keep_alives: bool,
add_repaint_boundaries: bool,
add_semantic_indexes: bool,
semantic_index_callback: &SemanticIndexCallback,
semantic_index_offset: i32,
) -> WidgetRef {
let key = child
.key()
.map(|key| KeyRef::from(SaltedValueKey::new(key.clone())));
let mut child = if add_repaint_boundaries {
RepaintBoundary::new().child(child).into_widget()
} else {
child
};
if add_semantic_indexes && let Some(semantic_index) = semantic_index_callback(&child, index) {
child = IndexedSemantics::new(semantic_index + semantic_index_offset)
.child(child)
.into_widget();
}
if add_automatic_keep_alives {
child = AutomaticKeepAlive::new(SelectionKeepAlive::new(child)).into_widget();
}
let subtree = KeyedSubtree::new(child);
match key {
Some(key) => subtree.key(key).into_widget(),
None => subtree.into_widget(),
}
}
pub type ChildIndexGetter = Rc<dyn Fn(&KeyRef) -> Option<i32>>;
#[derive(Clone)]
pub struct SliverChildBuilderDelegate {
pub builder: NullableIndexedWidgetBuilder,
pub child_count: Option<i32>,
pub add_automatic_keep_alives: bool,
pub add_repaint_boundaries: bool,
pub add_semantic_indexes: bool,
pub semantic_index_offset: i32,
pub semantic_index_callback: SemanticIndexCallback,
pub find_child_index_callback: Option<ChildIndexGetter>,
}
impl SliverChildBuilderDelegate {
pub fn new(
builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
) -> SliverChildBuilderDelegate {
SliverChildBuilderDelegate::from_builder(Rc::new(builder))
}
pub fn from_builder(builder: NullableIndexedWidgetBuilder) -> SliverChildBuilderDelegate {
SliverChildBuilderDelegate {
builder,
child_count: None,
add_automatic_keep_alives: true,
add_repaint_boundaries: true,
add_semantic_indexes: true,
semantic_index_offset: 0,
semantic_index_callback: default_semantic_index_callback(),
find_child_index_callback: None,
}
}
pub fn child_count(mut self, child_count: i32) -> SliverChildBuilderDelegate {
self.child_count = Some(child_count);
self
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverChildBuilderDelegate {
self.add_automatic_keep_alives = value;
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> SliverChildBuilderDelegate {
self.add_repaint_boundaries = value;
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> SliverChildBuilderDelegate {
self.add_semantic_indexes = value;
self
}
pub fn semantic_index_offset(mut self, value: i32) -> SliverChildBuilderDelegate {
self.semantic_index_offset = value;
self
}
pub fn semantic_index_callback(
mut self,
value: SemanticIndexCallback,
) -> SliverChildBuilderDelegate {
self.semantic_index_callback = value;
self
}
pub fn find_child_index_callback(
mut self,
value: ChildIndexGetter,
) -> SliverChildBuilderDelegate {
self.find_child_index_callback = Some(value);
self
}
pub fn into_delegate(self) -> SliverChildDelegateRef {
Rc::new(self)
}
}
impl SliverChildDelegate for SliverChildBuilderDelegate {
fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
let find_child_index_callback = self.find_child_index_callback.as_ref()?;
find_child_index_callback(&unsalt(key))
}
fn build(&self, app: &mut App, context: BuildContext, index: i32) -> Option<WidgetRef> {
if index < 0 || self.child_count.is_some_and(|count| index >= count) {
return None;
}
let child = (self.builder)(app, context, index)?;
Some(wrap_child(
child,
index,
self.add_automatic_keep_alives,
self.add_repaint_boundaries,
self.add_semantic_indexes,
&self.semantic_index_callback,
self.semantic_index_offset,
))
}
fn estimated_child_count(&self) -> Option<i32> {
self.child_count
}
fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool {
let _ = old_delegate;
true
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Debug for SliverChildBuilderDelegate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
self.debug_fill_description(&mut description);
write!(f, "SliverChildBuilderDelegate({})", description.join(", "))
}
}
pub struct SliverChildListDelegate {
pub add_automatic_keep_alives: bool,
pub add_repaint_boundaries: bool,
pub add_semantic_indexes: bool,
pub semantic_index_offset: i32,
pub semantic_index_callback: SemanticIndexCallback,
pub children: Vec<WidgetRef>,
key_to_index: Option<RefCell<KeyToIndex>>,
}
#[derive(Default)]
struct KeyToIndex {
map: HashMap<KeyRef, i32>,
cursor: usize,
}
impl SliverChildListDelegate {
pub fn new(children: Vec<WidgetRef>) -> SliverChildListDelegate {
SliverChildListDelegate {
add_automatic_keep_alives: true,
add_repaint_boundaries: true,
add_semantic_indexes: true,
semantic_index_offset: 0,
semantic_index_callback: default_semantic_index_callback(),
children,
key_to_index: Some(RefCell::default()),
}
}
pub fn fixed(children: Vec<WidgetRef>) -> SliverChildListDelegate {
SliverChildListDelegate {
key_to_index: None,
..SliverChildListDelegate::new(children)
}
}
pub fn add_automatic_keep_alives(mut self, value: bool) -> SliverChildListDelegate {
self.add_automatic_keep_alives = value;
self
}
pub fn add_repaint_boundaries(mut self, value: bool) -> SliverChildListDelegate {
self.add_repaint_boundaries = value;
self
}
pub fn add_semantic_indexes(mut self, value: bool) -> SliverChildListDelegate {
self.add_semantic_indexes = value;
self
}
pub fn semantic_index_offset(mut self, value: i32) -> SliverChildListDelegate {
self.semantic_index_offset = value;
self
}
pub fn semantic_index_callback(
mut self,
value: SemanticIndexCallback,
) -> SliverChildListDelegate {
self.semantic_index_callback = value;
self
}
pub fn into_delegate(self) -> SliverChildDelegateRef {
Rc::new(self)
}
fn find_child_index(&self, key: &KeyRef) -> Option<i32> {
let cache = self.key_to_index.as_ref()?;
let mut cache = cache.borrow_mut();
if let Some(index) = cache.map.get(key) {
return Some(*index);
}
let mut index = cache.cursor;
while index < self.children.len() {
let child = &self.children[index];
if let Some(child_key) = child.key() {
cache.map.insert(child_key.clone(), index as i32);
if child_key == key {
cache.cursor = index + 1;
return Some(index as i32);
}
}
index += 1;
}
cache.cursor = index;
None
}
}
impl SliverChildDelegate for SliverChildListDelegate {
fn find_index_by_key(&self, key: &KeyRef) -> Option<i32> {
self.find_child_index(&unsalt(key))
}
fn build(&self, _app: &mut App, _context: BuildContext, index: i32) -> Option<WidgetRef> {
let slot = usize::try_from(index).ok()?;
let child = self.children.get(slot)?.clone();
Some(wrap_child(
child,
index,
self.add_automatic_keep_alives,
self.add_repaint_boundaries,
self.add_semantic_indexes,
&self.semantic_index_callback,
self.semantic_index_offset,
))
}
fn estimated_child_count(&self) -> Option<i32> {
Some(self.children.len() as i32)
}
fn should_rebuild(&self, old_delegate: &dyn SliverChildDelegate) -> bool {
let old = old_delegate
.as_any()
.downcast_ref::<SliverChildListDelegate>()
.expect("the caller compared the delegate types first");
self.children.len() != old.children.len()
|| std::iter::zip(&self.children, &old.children).any(|(a, b)| !Rc::ptr_eq(a, b))
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl Debug for SliverChildListDelegate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut description = Vec::new();
self.debug_fill_description(&mut description);
write!(f, "SliverChildListDelegate({})", description.join(", "))
}
}