use std::any::{Any, TypeId};
use std::fmt::{Debug, Display};
use std::num::NonZeroU64;
use std::sync::atomic::{AtomicU64, Ordering};
use accesskit::{Node, Role};
use kurbo::{Axis, Point, Size};
use smallvec::SmallVec;
use tracing::field::DisplayValue;
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, AccessEvent, ActionCtx, ComposeCtx, CursorIcon, ErasedAction, EventCtx, LayoutCtx,
MeasureCtx, NewWidget, PaintCtx, PointerEvent, PropertiesMut, PropertiesRef, QueryCtx,
RegisterCtx, Subwindow, TextEvent, Update, UpdateCtx, WidgetMut, WidgetRef, pre_paint,
};
use crate::imaging::Painter;
use crate::layout::{LenReq, Length};
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub struct WidgetId(pub(crate) NonZeroU64);
impl WidgetId {
pub fn trace(self) -> DisplayValue<Self> {
tracing::field::display(self)
}
}
#[doc(hidden)]
pub trait AsDynWidget {
fn as_box_dyn(self: Box<Self>) -> Box<dyn Widget>;
fn as_dyn(&self) -> &dyn Widget;
fn as_mut_dyn(&mut self) -> &mut dyn Widget;
}
impl<T: Widget> AsDynWidget for T {
fn as_box_dyn(self: Box<Self>) -> Box<dyn Widget> {
self
}
fn as_dyn(&self) -> &dyn Widget {
self as &dyn Widget
}
fn as_mut_dyn(&mut self) -> &mut dyn Widget {
self as &mut dyn Widget
}
}
pub trait FromDynWidget {
fn from_dyn(widget: &dyn Widget) -> Option<&Self>;
fn from_dyn_mut(widget: &mut dyn Widget) -> Option<&mut Self>;
}
impl<T: Widget> FromDynWidget for T {
fn from_dyn(widget: &dyn Widget) -> Option<&Self> {
(widget as &dyn Any).downcast_ref()
}
fn from_dyn_mut(widget: &mut dyn Widget) -> Option<&mut Self> {
(widget as &mut dyn Any).downcast_mut()
}
}
impl FromDynWidget for dyn Widget {
fn from_dyn(widget: &dyn Widget) -> Option<&Self> {
Some(widget)
}
fn from_dyn_mut(widget: &mut dyn Widget) -> Option<&mut Self> {
Some(widget)
}
}
pub type ChildrenIds = SmallVec<[WidgetId; 16]>;
#[allow(unused_variables, reason = "Default impls don't use method arguments")]
pub trait Widget: AsDynWidget + Any {
type Action: Any + Debug
where
Self: Sized;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
}
fn on_text_event(
&mut self,
ctx: &mut EventCtx<'_>,
props: &mut PropertiesMut<'_>,
event: &TextEvent,
) {
}
fn on_access_event(
&mut self,
ctx: &mut EventCtx<'_>,
props: &mut PropertiesMut<'_>,
event: &AccessEvent,
) {
}
fn on_anim_frame(
&mut self,
ctx: &mut UpdateCtx<'_>,
props: &mut PropertiesMut<'_>,
interval: u64,
) {
}
fn on_action(
&mut self,
ctx: &mut ActionCtx<'_>,
props: &mut PropertiesMut<'_>,
action: &ErasedAction,
source: WidgetId,
) {
}
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>);
fn update(&mut self, ctx: &mut UpdateCtx<'_>, props: &mut PropertiesMut<'_>, event: &Update) {}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length;
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, props: &PropertiesRef<'_>, size: Size);
fn compose(&mut self, ctx: &mut ComposeCtx<'_>) {}
fn pre_paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
pre_paint(ctx, props, painter);
}
fn paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
);
fn post_paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
}
fn accessibility_role(&self) -> Role;
fn accessibility(
&mut self,
ctx: &mut AccessCtx<'_>,
props: &PropertiesRef<'_>,
node: &mut Node,
);
fn children_ids(&self) -> ChildrenIds;
fn as_subwindow(&mut self) -> Option<&mut dyn Subwindow> {
None
}
fn accepts_pointer_interaction(&self) -> bool {
true
}
fn accepts_tooltips(&self) -> bool {
false
}
fn propagates_pointer_interaction(&self) -> bool {
true
}
fn accepts_focus(&self) -> bool {
false
}
fn accepts_text_input(&self) -> bool {
false
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Widget", r#type = self.short_type_name(), id = id.trace())
}
fn get_debug_text(&self) -> Option<String> {
None
}
fn get_cursor(&self, ctx: &QueryCtx<'_>, pos: Point) -> CursorIcon {
CursorIcon::Default
}
fn find_widget_under_pointer<'c>(
&'c self,
ctx: QueryCtx<'c>,
pos: Point,
) -> Option<WidgetRef<'c, dyn Widget>> {
find_widget_under_pointer(self.as_dyn(), ctx, pos)
}
#[doc(hidden)]
fn type_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
#[doc(hidden)]
fn short_type_name(&self) -> &'static str {
let name = self.type_name();
name.split('<')
.next()
.unwrap_or(name)
.split("::")
.last()
.unwrap_or(name)
}
fn prepare(self) -> NewWidget<Self>
where
Self: Sized,
{
NewWidget::new(self)
}
}
pub fn find_widget_under_pointer<'c>(
widget: &'c dyn Widget,
ctx: QueryCtx<'c>,
pos: Point,
) -> Option<WidgetRef<'c, dyn Widget>> {
if !ctx.bounding_box().contains(pos) {
return None;
}
if ctx.is_stashed() {
return None;
}
let local_pos = ctx.to_local(pos);
if let Some(clip) = ctx.clip_path()
&& !clip.contains(local_pos)
{
return None;
}
if ctx.propagates_pointer_interaction() {
for child_id in widget.children_ids().iter().rev() {
let child_ref = ctx.get(*child_id);
if let Some(child) = child_ref
.widget
.find_widget_under_pointer(child_ref.ctx, pos)
{
return Some(child);
}
}
}
if !ctx.accepts_pointer_interaction() {
return None;
}
if !ctx.border_box().contains(local_pos) {
return None;
}
Some(WidgetRef { widget, ctx })
}
pub trait AllowRawMut: Widget {}
impl WidgetId {
pub(crate) fn next() -> Self {
static WIDGET_ID_COUNTER: AtomicU64 = AtomicU64::new(1);
let id = WIDGET_ID_COUNTER.fetch_add(1, Ordering::Relaxed);
Self(id.try_into().unwrap())
}
pub fn to_raw(self) -> u64 {
self.0.into()
}
}
impl From<WidgetId> for u64 {
fn from(id: WidgetId) -> Self {
id.0.into()
}
}
impl From<WidgetId> for accesskit::NodeId {
fn from(id: WidgetId) -> Self {
Self(id.0.into())
}
}
impl Display for WidgetId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "#{}", self.0)
}
}
impl PartialEq<accesskit::NodeId> for WidgetId {
fn eq(&self, other: &accesskit::NodeId) -> bool {
self.to_raw() == other.0
}
}
impl PartialEq<WidgetId> for accesskit::NodeId {
fn eq(&self, other: &WidgetId) -> bool {
self.0 == other.to_raw()
}
}
pub trait CollectionWidget<Params>: Widget {
fn len(&self) -> usize;
fn is_empty(&self) -> bool;
fn get_mut<'t>(this: &'t mut WidgetMut<'_, Self>, idx: usize) -> WidgetMut<'t, dyn Widget>;
fn add(
this: &mut WidgetMut<'_, Self>,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<Params>,
);
fn insert(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<Params>,
);
fn set(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
params: impl Into<Params>,
);
fn set_params(this: &mut WidgetMut<'_, Self>, idx: usize, params: impl Into<Params>);
fn swap(this: &mut WidgetMut<'_, Self>, a: usize, b: usize);
fn remove(this: &mut WidgetMut<'_, Self>, idx: usize);
fn clear(this: &mut WidgetMut<'_, Self>);
}