use std::any::{Any, TypeId};
use std::fmt::{self, Debug};
use std::hash::{Hash, Hasher};
use std::rc::Rc;
use waft_foundation::{App, HandleId, Key};
use waft_rendering::{
AnyRenderObject, ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject,
RenderObjectWithChildMixin,
};
use super::element::{AnyElement, BuildContext, Element};
use super::elements::{
InheritedElement, LeafRenderObjectElement, MultiChildRenderObjectElement, ParentDataElement,
SingleChildRenderObjectElement, StatefulElement, StatelessElement,
};
use super::state::State;
use crate::widgets::inherited_theme::InheritedTheme;
use crate::widgets::preferred_size::PreferredSizeWidget;
#[derive(Clone)]
pub enum KeyRef {
Local(Rc<dyn Key>),
Global(GlobalKey),
}
impl KeyRef {
pub fn key(&self) -> &dyn Key {
match self {
KeyRef::Local(key) => &**key,
KeyRef::Global(global) => global.key(),
}
}
}
impl PartialEq for KeyRef {
fn eq(&self, other: &KeyRef) -> bool {
match (self, other) {
(KeyRef::Local(a), KeyRef::Local(b)) => **a == **b,
(KeyRef::Global(a), KeyRef::Global(b)) => a == b,
_ => false,
}
}
}
impl Eq for KeyRef {}
impl Hash for KeyRef {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
self.key().hash(state);
}
}
impl Debug for KeyRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
KeyRef::Local(key) => key.fmt(f),
KeyRef::Global(global) => global.fmt(f),
}
}
}
impl<K: Key> From<K> for KeyRef {
fn from(key: K) -> KeyRef {
KeyRef::Local(Rc::new(key))
}
}
impl From<GlobalKey> for KeyRef {
fn from(key: GlobalKey) -> KeyRef {
KeyRef::Global(key)
}
}
pub type WidgetRef = Rc<dyn Widget>;
impl PartialEq for dyn Widget {
fn eq(&self, other: &dyn Widget) -> bool {
std::ptr::addr_eq(self as *const dyn Widget, other as *const dyn Widget)
}
}
pub trait Widget: Any + Debug {
fn key(&self) -> Option<&KeyRef>;
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement;
fn as_any(&self) -> &dyn Any;
fn widget_type(&self) -> TypeId;
fn type_name(&self) -> &'static str {
short_type_name::<Self>()
}
fn kind(&self) -> WidgetKind;
fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
None
}
fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
None
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WidgetKind {
Stateful,
Stateless,
Other,
}
pub fn can_update(old_widget: &dyn Widget, new_widget: &dyn Widget) -> bool {
old_widget.widget_type() == new_widget.widget_type()
&& keys_equal(old_widget.key(), new_widget.key())
}
pub fn keys_equal(a: Option<&KeyRef>, b: Option<&KeyRef>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => a == b,
_ => false,
}
}
pub fn same_widget(a: &WidgetRef, b: &WidgetRef) -> bool {
Rc::ptr_eq(a, b)
}
pub fn downcast_widget<W: 'static>(widget: &dyn Widget) -> Option<&W> {
widget.as_any().downcast_ref::<W>()
}
pub fn short_type_name<W: ?Sized>() -> &'static str {
let name = std::any::type_name::<W>();
let type_arguments = name.find('<').unwrap_or(name.len());
let own_name = name[..type_arguments]
.rfind("::")
.map_or(0, |path_end| path_end + 2);
&name[own_name..]
}
pub trait IntoWidget<Kind> {
fn into_widget(self) -> WidgetRef;
}
pub struct WidgetRefKind;
impl IntoWidget<WidgetRefKind> for WidgetRef {
fn into_widget(self) -> WidgetRef {
self
}
}
pub struct TreeNodeKind;
impl<W: Widget> IntoWidget<TreeNodeKind> for W {
fn into_widget(self) -> WidgetRef {
Rc::new(self)
}
}
pub trait StatelessWidget: Debug + 'static {
fn key(&self) -> Option<&KeyRef> {
None
}
fn debug_check_constructor(&self) {}
fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
None
}
fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef;
}
pub struct StatelessKind;
pub struct Stateless<W: StatelessWidget>(pub W);
impl<W: StatelessWidget> IntoWidget<StatelessKind> for W {
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
self.debug_check_constructor();
}
Rc::new(Stateless(self))
}
}
impl<W: StatelessWidget> Widget for Stateless<W> {
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
StatelessElement::<W>::new(app, this).as_element()
}
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::Stateless
}
fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
self.0.as_preferred_size_widget()
}
}
impl<W: StatelessWidget> Debug for Stateless<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait StatefulWidget: Debug + 'static {
type State: State<Widget = Self>;
fn key(&self) -> Option<&KeyRef> {
None
}
fn debug_check_constructor(&self) {}
fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
None
}
fn type_name(&self) -> &'static str {
short_type_name::<Self>()
}
fn create_state(&self) -> Self::State;
}
pub struct StatefulKind;
pub struct Stateful<W: StatefulWidget>(pub W);
impl<W: StatefulWidget> IntoWidget<StatefulKind> for W {
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
self.debug_check_constructor();
}
Rc::new(Stateful(self))
}
}
impl<W: StatefulWidget> Widget for Stateful<W> {
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
StatefulElement::<W>::new(app, this).as_element()
}
fn as_any(&self) -> &dyn Any {
&self.0
}
fn widget_type(&self) -> TypeId {
TypeId::of::<W>()
}
fn type_name(&self) -> &'static str {
StatefulWidget::type_name(&self.0)
}
fn kind(&self) -> WidgetKind {
WidgetKind::Stateful
}
fn as_preferred_size_widget(&self) -> Option<&dyn PreferredSizeWidget> {
self.0.as_preferred_size_widget()
}
}
impl<W: StatefulWidget> Debug for Stateful<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait InheritedWidget: Debug + 'static {
fn key(&self) -> Option<&KeyRef> {
None
}
fn debug_check_constructor(&self) {}
fn child(&self) -> &WidgetRef;
fn update_should_notify(&self, old_widget: &Self) -> bool;
fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
None
}
}
pub struct InheritedKind;
pub struct Inherited<W: InheritedWidget>(pub W);
impl<W: InheritedWidget> IntoWidget<InheritedKind> for W {
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
self.debug_check_constructor();
}
Rc::new(Inherited(self))
}
}
impl<W: InheritedWidget> Widget for Inherited<W> {
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
InheritedElement::<W>::new(app, this).as_element()
}
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 as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
self.0.as_inherited_theme()
}
}
impl<W: InheritedWidget> Debug for Inherited<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait ParentDataWidget: Debug + 'static {
type ParentData: ParentData + 'static;
fn key(&self) -> Option<&KeyRef> {
None
}
fn debug_check_constructor(&self) {}
fn child(&self) -> &WidgetRef;
fn apply_parent_data(&self, app: &mut App, render_object: AnyRenderObject);
fn debug_is_valid_render_object(
&self,
app: &App,
render_object: ::waft_rendering::AnyRenderObject,
) -> bool {
render_object.parent_data_is::<Self::ParentData>(app)
}
fn debug_can_apply_out_of_turn(&self) -> bool {
false
}
}
pub struct ParentDataKind;
pub struct ParentDataWrapper<W: ParentDataWidget>(pub W);
impl<W: ParentDataWidget> IntoWidget<ParentDataKind> for W {
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
self.debug_check_constructor();
}
Rc::new(ParentDataWrapper(self))
}
}
impl<W: ParentDataWidget> Widget for ParentDataWrapper<W> {
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
ParentDataElement::<W>::new(app, this).as_element()
}
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
}
}
impl<W: ParentDataWidget> Debug for ParentDataWrapper<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait RenderObjectWidget: Debug + 'static {
type RenderObject: RenderObject;
fn key(&self) -> Option<&KeyRef> {
None
}
fn debug_check_constructor(&self) {}
fn debug_visit_onstage_children(
&self,
app: &App,
children: &[AnyElement],
visitor: &mut dyn FnMut(AnyElement),
) {
let _ = app;
children.iter().for_each(|child| visitor(*child));
}
fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject;
fn update_render_object(
&self,
app: &mut App,
context: BuildContext,
render_object: RenderHandle<Self::RenderObject>,
) {
let _ = (app, context, render_object);
}
fn did_unmount_render_object(
&self,
app: &mut App,
render_object: RenderHandle<Self::RenderObject>,
) {
let _ = (app, render_object);
}
}
pub trait LeafRenderObjectWidget: RenderObjectWidget {}
pub struct LeafRenderObjectKind;
pub struct LeafRenderObject<W: LeafRenderObjectWidget>(pub W);
impl<W: LeafRenderObjectWidget> IntoWidget<LeafRenderObjectKind> for W {
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
RenderObjectWidget::debug_check_constructor(&self);
}
Rc::new(LeafRenderObject(self))
}
}
impl<W: LeafRenderObjectWidget> Widget for LeafRenderObject<W> {
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
LeafRenderObjectElement::<W>::new(app, this).as_element()
}
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
}
}
impl<W: LeafRenderObjectWidget> Debug for LeafRenderObject<W> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait SingleChildRenderObjectWidget: RenderObjectWidget
where
Self::RenderObject: RenderObjectWithChildMixin,
{
fn child(&self) -> Option<&WidgetRef>;
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
where
Self: Sized,
{
SingleChildRenderObjectElement::<Self>::new(app, this).as_element()
}
}
pub struct SingleChildRenderObjectKind;
pub struct SingleChildRenderObject<W: SingleChildRenderObjectWidget>(pub W)
where
W::RenderObject: RenderObjectWithChildMixin;
impl<W: SingleChildRenderObjectWidget> IntoWidget<SingleChildRenderObjectKind> for W
where
W::RenderObject: RenderObjectWithChildMixin,
{
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
RenderObjectWidget::debug_check_constructor(&self);
}
Rc::new(SingleChildRenderObject(self))
}
}
impl<W: SingleChildRenderObjectWidget> Widget for SingleChildRenderObject<W>
where
W::RenderObject: RenderObjectWithChildMixin,
{
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
SingleChildRenderObjectWidget::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
}
}
impl<W: SingleChildRenderObjectWidget> Debug for SingleChildRenderObject<W>
where
W::RenderObject: RenderObjectWithChildMixin,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
pub trait MultiChildRenderObjectWidget: RenderObjectWidget
where
Self::RenderObject: ContainerRenderObjectMixin,
{
fn children(&self) -> &[WidgetRef];
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement
where
Self: Sized,
{
MultiChildRenderObjectElement::<Self>::new(app, this).as_element()
}
}
pub struct MultiChildRenderObjectKind;
pub struct MultiChildRenderObject<W: MultiChildRenderObjectWidget>(pub W)
where
W::RenderObject: ContainerRenderObjectMixin;
impl<W: MultiChildRenderObjectWidget> IntoWidget<MultiChildRenderObjectKind> for W
where
W::RenderObject: ContainerRenderObjectMixin,
{
fn into_widget(self) -> WidgetRef {
if cfg!(debug_assertions) {
RenderObjectWidget::debug_check_constructor(&self);
}
Rc::new(MultiChildRenderObject(self))
}
}
impl<W: MultiChildRenderObjectWidget> Widget for MultiChildRenderObject<W>
where
W::RenderObject: ContainerRenderObjectMixin,
{
fn key(&self) -> Option<&KeyRef> {
self.0.key()
}
fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
MultiChildRenderObjectWidget::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
}
}
impl<W: MultiChildRenderObjectWidget> Debug for MultiChildRenderObject<W>
where
W::RenderObject: ContainerRenderObjectMixin,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Clone)]
pub struct GlobalKey {
key: Rc<dyn Key>,
}
impl GlobalKey {
#[expect(
clippy::new_without_default,
reason = "each call creates a distinct key; Default would suggest a neutral value"
)]
pub fn new() -> GlobalKey {
GlobalKey::wrapping(Rc::new(LabeledGlobalKeyValue::new(None)))
}
pub fn labeled(debug_label: impl Into<String>) -> GlobalKey {
GlobalKey::wrapping(Rc::new(LabeledGlobalKeyValue::new(Some(
debug_label.into(),
))))
}
pub fn object(value: impl Into<HandleId>) -> GlobalKey {
GlobalKey::wrapping(Rc::new(GlobalObjectKeyValue {
value: value.into(),
}))
}
pub fn wrapping(key: Rc<dyn Key>) -> GlobalKey {
GlobalKey { key }
}
pub fn key(&self) -> &dyn Key {
&*self.key
}
pub fn current_context(&self, app: &App) -> Option<BuildContext> {
self.current_element(app)
}
pub fn current_widget(&self, app: &App) -> Option<WidgetRef> {
let element = self.current_element(app)?;
Some(element.widget(app).clone())
}
pub fn current_state<S: State>(&self, app: &App) -> Option<waft_foundation::Handle<S>> {
let element = self.current_element(app)?;
element.state_handle::<S>(app)
}
fn current_element(&self, app: &App) -> Option<AnyElement> {
let owner = crate::binding::current_build_owner(app)?;
owner.global_key_element(app, self)
}
}
impl PartialEq for GlobalKey {
fn eq(&self, other: &GlobalKey) -> bool {
*self.key == *other.key
}
}
impl Eq for GlobalKey {}
impl Hash for GlobalKey {
fn hash<H: Hasher>(&self, state: &mut H) {
self.key.hash(state);
}
}
impl Debug for GlobalKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.key.fmt(f)
}
}
struct LabeledGlobalKeyValue {
unique: waft_foundation::UniqueKey,
debug_label: Option<String>,
}
impl LabeledGlobalKeyValue {
fn new(debug_label: Option<String>) -> LabeledGlobalKeyValue {
LabeledGlobalKeyValue {
unique: waft_foundation::UniqueKey::new(),
debug_label,
}
}
}
impl Key for LabeledGlobalKeyValue {
fn eq_key(&self, other: &dyn Key) -> bool {
(other as &dyn Any)
.downcast_ref::<LabeledGlobalKeyValue>()
.is_some_and(|other| other.unique == self.unique)
}
fn hash_key(&self, mut state: &mut dyn Hasher) {
TypeId::of::<LabeledGlobalKeyValue>().hash(&mut state);
self.unique.hash(&mut state);
}
}
impl Debug for LabeledGlobalKeyValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let id = std::ptr::from_ref(self) as usize & 0xF_FFFF;
match &self.debug_label {
Some(label) => write!(f, "[GlobalKey#{id:05x} {label}]"),
None => write!(f, "[GlobalKey#{id:05x}]"),
}
}
}
struct GlobalObjectKeyValue {
value: HandleId,
}
impl Key for GlobalObjectKeyValue {
fn eq_key(&self, other: &dyn Key) -> bool {
(other as &dyn Any)
.downcast_ref::<GlobalObjectKeyValue>()
.is_some_and(|other| other.value == self.value)
}
fn hash_key(&self, mut state: &mut dyn Hasher) {
TypeId::of::<GlobalObjectKeyValue>().hash(&mut state);
self.value.hash(&mut state);
}
}
impl Debug for GlobalObjectKeyValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "[GlobalObjectKey {:?}]", self.value)
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectKey {
pub value: Option<HandleId>,
}
impl ObjectKey {
pub const fn new(value: Option<HandleId>) -> ObjectKey {
ObjectKey { value }
}
}
impl Key for ObjectKey {
fn eq_key(&self, other: &dyn Key) -> bool {
(other as &dyn Any)
.downcast_ref::<ObjectKey>()
.is_some_and(|other| other.value == self.value)
}
fn hash_key(&self, mut state: &mut dyn Hasher) {
TypeId::of::<ObjectKey>().hash(&mut state);
self.value.hash(&mut state);
}
}
impl waft_foundation::LocalKey for ObjectKey {}
impl Debug for ObjectKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.value {
Some(value) => write!(f, "[{value:?}]"),
None => f.write_str("[null]"),
}
}
}