use std::{any::Any, cell::Cell, fmt, hash::Hash, rc::Rc};
pub use cranpose_ui_graphics::{DrawScope, Size};
pub use cranpose_ui_layout::{Constraints, Measurable};
use crate::nodes::input::types::PointerEvent;
mod any_element;
mod chain;
mod chain_node_ref;
mod node_capabilities;
mod node_element;
mod scroll_axis_range;
mod semantics_configuration;
pub use any_element::*;
pub use chain::*;
pub use chain_node_ref::{ModifierChainIter, ModifierChainNodeRef};
pub use node_capabilities::NodeCapabilities;
pub use node_element::ModifierNodeElement;
pub use scroll_axis_range::ScrollAxisRange;
pub use semantics_configuration::{SemanticsConfiguration, SemanticsSpec};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum InvalidationKind {
Layout,
Draw,
PointerInput,
Semantics,
Focus,
}
pub trait ModifierNodeContext {
fn invalidate(&mut self, _kind: InvalidationKind) {}
fn request_update(&mut self) {}
fn node_id(&self) -> Option<cranpose_core::NodeId> {
None
}
fn push_active_capabilities(&mut self, _capabilities: NodeCapabilities) {}
fn pop_active_capabilities(&mut self) {}
fn density(&self) -> f32 {
1.0
}
}
#[derive(Default, Debug, Clone)]
pub struct BasicModifierNodeContext {
invalidations: ModifierInvalidations,
update_requested: bool,
active_capabilities: smallvec::SmallVec<[NodeCapabilities; 4]>,
node_id: Option<cranpose_core::NodeId>,
}
impl BasicModifierNodeContext {
pub fn new() -> Self {
Self::default()
}
pub fn for_node(
node_id: Option<cranpose_core::NodeId>,
invalidations: ModifierInvalidations,
) -> Self {
Self {
invalidations,
node_id,
..Self::default()
}
}
pub fn invalidations(&self) -> &[ModifierInvalidation] {
&self.invalidations
}
pub fn clear_invalidations(&mut self) {
self.invalidations.clear();
}
pub fn take_invalidations(&mut self) -> ModifierInvalidations {
std::mem::take(&mut self.invalidations)
}
pub fn update_requested(&self) -> bool {
self.update_requested
}
pub fn take_update_requested(&mut self) -> bool {
std::mem::take(&mut self.update_requested)
}
pub fn set_node_id(&mut self, id: Option<cranpose_core::NodeId>) {
self.node_id = id;
}
fn push_invalidation(&mut self, kind: InvalidationKind) {
let mut capabilities = self.current_capabilities();
capabilities.insert(NodeCapabilities::for_invalidation(kind));
if let Some(existing) = self
.invalidations
.iter_mut()
.find(|entry| entry.kind() == kind)
{
let updated = existing.capabilities() | capabilities;
*existing = ModifierInvalidation::new(kind, updated);
} else {
self.invalidations
.push(ModifierInvalidation::new(kind, capabilities));
}
}
fn current_capabilities(&self) -> NodeCapabilities {
self.active_capabilities
.last()
.copied()
.unwrap_or_else(NodeCapabilities::empty)
}
}
impl ModifierNodeContext for BasicModifierNodeContext {
fn invalidate(&mut self, kind: InvalidationKind) {
self.push_invalidation(kind);
}
fn request_update(&mut self) {
self.update_requested = true;
}
fn push_active_capabilities(&mut self, capabilities: NodeCapabilities) {
self.active_capabilities.push(capabilities);
}
fn pop_active_capabilities(&mut self) {
self.active_capabilities.pop();
}
fn node_id(&self) -> Option<cranpose_core::NodeId> {
self.node_id
}
}
const MAX_DELEGATE_DEPTH: usize = 3;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub(crate) struct NodePath {
entry: u32,
delegate_buf: [u8; MAX_DELEGATE_DEPTH],
delegate_len: u8,
}
impl NodePath {
#[inline]
fn root(entry: usize) -> Self {
debug_assert!(entry <= u32::MAX as usize, "chain entry exceeds u32 range");
Self {
entry: entry as u32,
delegate_buf: [0; MAX_DELEGATE_DEPTH],
delegate_len: 0,
}
}
#[inline]
fn from_slice(entry: usize, path: &[usize]) -> Self {
debug_assert!(
path.len() <= MAX_DELEGATE_DEPTH,
"delegate depth {} exceeds MAX_DELEGATE_DEPTH {}",
path.len(),
MAX_DELEGATE_DEPTH
);
debug_assert!(
path.iter().all(|&i| i <= u8::MAX as usize),
"delegate index exceeds u8 range"
);
let mut delegate_buf = [0u8; MAX_DELEGATE_DEPTH];
for (i, &v) in path.iter().enumerate().take(MAX_DELEGATE_DEPTH) {
delegate_buf[i] = v as u8;
}
Self {
delegate_buf,
delegate_len: path.len().min(MAX_DELEGATE_DEPTH) as u8,
..Self::root(entry)
}
}
#[inline]
fn entry(&self) -> usize {
self.entry as usize
}
#[inline]
fn delegates(&self) -> &[u8] {
&self.delegate_buf[..self.delegate_len as usize]
}
}
#[derive(Debug)]
pub struct NodeState {
capabilities: Cell<NodeCapabilities>,
attached: Cell<bool>,
}
impl Default for NodeState {
fn default() -> Self {
Self::new()
}
}
impl NodeState {
pub const fn new() -> Self {
Self {
capabilities: Cell::new(NodeCapabilities::empty()),
attached: Cell::new(false),
}
}
pub fn set_capabilities(&self, capabilities: NodeCapabilities) {
self.capabilities.set(capabilities);
}
#[inline]
pub fn capabilities(&self) -> NodeCapabilities {
self.capabilities.get()
}
pub(crate) fn set_attached(&self, attached: bool) {
self.attached.set(attached);
}
pub fn is_attached(&self) -> bool {
self.attached.get()
}
}
pub trait DelegatableNode {
fn node_state(&self) -> &NodeState;
}
pub trait ModifierNode: Any + DelegatableNode {
fn on_attach(&mut self, _context: &mut dyn ModifierNodeContext) {}
fn on_detach(&mut self) {}
fn on_reset(&mut self) {}
fn as_draw_node(&self) -> Option<&dyn DrawModifierNode> {
None
}
fn as_draw_node_mut(&mut self) -> Option<&mut dyn DrawModifierNode> {
None
}
fn as_pointer_input_node(&self) -> Option<&dyn PointerInputNode> {
None
}
fn as_pointer_input_node_mut(&mut self) -> Option<&mut dyn PointerInputNode> {
None
}
fn as_semantics_node(&self) -> Option<&dyn SemanticsNode> {
None
}
fn as_semantics_node_mut(&mut self) -> Option<&mut dyn SemanticsNode> {
None
}
fn as_focus_node(&self) -> Option<&dyn FocusNode> {
None
}
fn as_focus_node_mut(&mut self) -> Option<&mut dyn FocusNode> {
None
}
fn as_layout_node(&self) -> Option<&dyn LayoutModifierNode> {
None
}
fn as_layout_node_mut(&mut self) -> Option<&mut dyn LayoutModifierNode> {
None
}
fn for_each_delegate<'b>(&'b self, _visitor: &mut dyn FnMut(&'b dyn ModifierNode)) {}
fn for_each_delegate_mut<'b>(&'b mut self, _visitor: &mut dyn FnMut(&'b mut dyn ModifierNode)) {
}
}
pub trait LayoutModifierNode: ModifierNode {
fn measure(
&self,
_context: &mut dyn ModifierNodeContext,
measurable: &dyn Measurable,
constraints: Constraints,
) -> cranpose_ui_layout::LayoutModifierMeasureResult {
let placeable = measurable.measure(constraints);
cranpose_ui_layout::LayoutModifierMeasureResult::with_size(Size {
width: placeable.width(),
height: placeable.height(),
})
}
fn measure_hold(
&self,
_density: f32,
_constraints: Constraints,
_size: Size,
_wrapped: cranpose_ui_layout::WrappedHold,
) -> Option<cranpose_ui_layout::ConstraintsHold> {
None
}
fn min_intrinsic_width(&self, measurable: &dyn Measurable, height: f32, _density: f32) -> f32 {
measurable.min_intrinsic_width(height)
}
fn max_intrinsic_width(&self, measurable: &dyn Measurable, height: f32, _density: f32) -> f32 {
measurable.max_intrinsic_width(height)
}
fn min_intrinsic_height(&self, measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
measurable.min_intrinsic_height(width)
}
fn max_intrinsic_height(&self, measurable: &dyn Measurable, width: f32, _density: f32) -> f32 {
measurable.max_intrinsic_height(width)
}
}
pub trait DrawModifierNode: ModifierNode {
fn create_draw_closure(&self) -> Option<NodeDrawClosure> {
None
}
fn create_behind_draw_closure(&self) -> Option<NodeDrawClosure> {
None
}
}
pub type NodeDrawClosure = Rc<dyn Fn(&mut cranpose_ui_graphics::DrawScopeDefault)>;
pub trait PointerInputNode: ModifierNode {
fn on_pointer_event(
&mut self,
_context: &mut dyn ModifierNodeContext,
_event: &PointerEvent,
) -> bool {
false
}
fn hit_test(&self, _x: f32, _y: f32) -> bool {
true
}
fn pointer_input_handler(&self) -> Option<Rc<dyn Fn(PointerEvent)>> {
None
}
fn layout_size_sink(&self) -> Option<Rc<Cell<Size>>> {
None
}
}
pub trait SemanticsNode: ModifierNode {
fn merge_semantics(&self, _config: &mut SemanticsConfiguration) {}
fn reach(&self) -> SemanticsReach {
SemanticsReach::merged_by(self, true)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SemanticsReach {
pub is_modal: bool,
pub hidden: bool,
pub merges_live_state: bool,
}
impl SemanticsReach {
pub fn merged_by(node: &(impl SemanticsNode + ?Sized), merges_live_state: bool) -> Self {
let mut config = SemanticsConfiguration::default();
node.merge_semantics(&mut config);
Self {
is_modal: config.is_modal,
hidden: config.hidden,
merges_live_state,
}
}
pub fn union(self, other: Self) -> Self {
Self {
is_modal: self.is_modal || other.is_modal,
hidden: self.hidden || other.hidden,
merges_live_state: self.merges_live_state || other.merges_live_state,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ToggleableState {
On,
Off,
Indeterminate,
}
impl From<bool> for ToggleableState {
fn from(on: bool) -> Self {
if on { Self::On } else { Self::Off }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum FocusState {
Active,
ActiveParent,
Captured,
#[default]
Inactive,
}
impl FocusState {
pub fn is_focused(self) -> bool {
matches!(self, Self::Active | Self::Captured)
}
pub fn has_focus(self) -> bool {
matches!(self, Self::Active | Self::ActiveParent | Self::Captured)
}
pub fn is_captured(self) -> bool {
matches!(self, Self::Captured)
}
}
pub trait FocusNode: ModifierNode {
fn focus_state(&self) -> FocusState;
fn on_focus_changed(&mut self, _context: &mut dyn ModifierNodeContext, _state: FocusState) {}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SemanticsWidgetRole {
Button,
Checkbox,
Switch,
RadioButton,
Tab,
Image,
DropdownList,
ValuePicker,
Header,
Dialog,
Link,
SearchField,
ProgressBar,
ToggleButton,
Alert,
Toolbar,
Menu,
MenuItem,
TabBar,
List,
ListItem,
RadioGroup,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ProgressBarRangeInfo {
pub current: f32,
pub start: f32,
pub end: f32,
pub steps: u32,
}
impl ProgressBarRangeInfo {
pub fn new(current: f32, start: f32, end: f32, steps: u32) -> Self {
Self {
current,
start,
end,
steps,
}
}
pub fn fraction(&self) -> f32 {
let span = self.end - self.start;
if span.abs() < f32::EPSILON {
return 0.0;
}
((self.current - self.start) / span).clamp(0.0, 1.0)
}
pub fn step(&self) -> f32 {
let span = self.end - self.start;
if self.steps == 0 {
span / 10.0
} else {
span / (self.steps as f32 + 1.0)
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CollectionInfo {
pub rows: usize,
pub columns: usize,
}
#[derive(Clone)]
pub struct SemanticsScrollBy {
handler: Rc<dyn Fn(f32, f32) -> bool>,
}
impl SemanticsScrollBy {
pub fn new(handler: impl Fn(f32, f32) -> bool + 'static) -> Self {
Self {
handler: Rc::new(handler),
}
}
pub fn invoke(&self, dx: f32, dy: f32) -> bool {
(self.handler)(dx, dy)
}
}
impl fmt::Debug for SemanticsScrollBy {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SemanticsScrollBy").finish_non_exhaustive()
}
}
impl PartialEq for SemanticsScrollBy {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for SemanticsScrollBy {}
#[derive(Clone)]
pub struct SemanticsScrollToIndex {
handler: Rc<dyn Fn(usize) -> bool>,
}
impl SemanticsScrollToIndex {
pub fn new(handler: impl Fn(usize) -> bool + 'static) -> Self {
Self {
handler: Rc::new(handler),
}
}
pub fn invoke(&self, index: usize) -> bool {
(self.handler)(index)
}
}
impl fmt::Debug for SemanticsScrollToIndex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SemanticsScrollToIndex")
.finish_non_exhaustive()
}
}
impl PartialEq for SemanticsScrollToIndex {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for SemanticsScrollToIndex {}
#[derive(Clone)]
pub struct SemanticsSetProgress {
handler: Rc<dyn Fn(f32) -> bool>,
}
impl SemanticsSetProgress {
pub fn new(handler: impl Fn(f32) -> bool + 'static) -> Self {
Self {
handler: Rc::new(handler),
}
}
pub fn invoke(&self, value: f32) -> bool {
(self.handler)(value)
}
}
impl fmt::Debug for SemanticsSetProgress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SemanticsSetProgress")
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct SemanticsSetText(Rc<dyn Fn(&str) -> bool>);
impl SemanticsSetText {
pub fn new(handler: impl Fn(&str) -> bool + 'static) -> Self {
Self(Rc::new(handler))
}
pub fn invoke(&self, text: &str) -> bool {
(self.0)(text)
}
}
impl fmt::Debug for SemanticsSetText {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SemanticsSetText")
}
}
#[derive(Clone)]
pub struct SemanticsSetSelection(Rc<dyn Fn(usize, usize) -> bool>);
impl SemanticsSetSelection {
pub fn new(handler: impl Fn(usize, usize) -> bool + 'static) -> Self {
Self(Rc::new(handler))
}
pub fn invoke(&self, anchor: usize, focus: usize) -> bool {
(self.0)(anchor, focus)
}
}
impl fmt::Debug for SemanticsSetSelection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SemanticsSetSelection")
}
}
#[derive(Clone)]
pub struct SemanticsExpand(Rc<dyn Fn() -> bool>);
impl SemanticsExpand {
pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
Self(Rc::new(handler))
}
pub fn invoke(&self) -> bool {
(self.0)()
}
}
impl fmt::Debug for SemanticsExpand {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SemanticsExpand")
}
}
#[derive(Clone)]
pub struct SemanticsLongClick(Rc<dyn Fn() -> bool>);
impl SemanticsLongClick {
pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
Self(Rc::new(handler))
}
pub fn invoke(&self) -> bool {
(self.0)()
}
}
impl fmt::Debug for SemanticsLongClick {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SemanticsLongClick")
}
}
impl PartialEq for SemanticsLongClick {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl PartialEq for SemanticsExpand {
fn eq(&self, _other: &Self) -> bool {
true
}
}
#[derive(Clone)]
pub struct SemanticsDismiss(Rc<dyn Fn() -> bool>);
impl SemanticsDismiss {
pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
Self(Rc::new(handler))
}
pub fn invoke(&self) -> bool {
(self.0)()
}
}
impl fmt::Debug for SemanticsDismiss {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SemanticsDismiss")
}
}
impl PartialEq for SemanticsDismiss {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl PartialEq for SemanticsSetText {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl PartialEq for SemanticsSetSelection {
fn eq(&self, _other: &Self) -> bool {
true
}
}
#[derive(Clone)]
pub struct SemanticsMagicTap(Rc<dyn Fn() -> bool>);
impl SemanticsMagicTap {
pub fn new(handler: impl Fn() -> bool + 'static) -> Self {
Self(Rc::new(handler))
}
pub fn invoke(&self) -> bool {
(self.0)()
}
}
impl fmt::Debug for SemanticsMagicTap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("SemanticsMagicTap")
}
}
impl PartialEq for SemanticsMagicTap {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl PartialEq for SemanticsSetProgress {
fn eq(&self, _other: &Self) -> bool {
true
}
}
impl Eq for SemanticsSetProgress {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LiveRegionMode {
Polite,
Assertive,
}
#[derive(Clone)]
pub struct SemanticsCustomAction {
pub label: String,
handler: Rc<dyn Fn()>,
}
impl SemanticsCustomAction {
pub fn new(label: impl Into<String>, handler: impl Fn() + 'static) -> Self {
Self {
label: label.into(),
handler: Rc::new(handler),
}
}
pub fn invoke(&self) {
(self.handler)();
}
}
impl fmt::Debug for SemanticsCustomAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SemanticsCustomAction")
.field("label", &self.label)
.finish_non_exhaustive()
}
}
impl PartialEq for SemanticsCustomAction {
fn eq(&self, other: &Self) -> bool {
self.label == other.label
}
}
impl Eq for SemanticsCustomAction {}
#[derive(Clone, Debug, PartialEq)]
pub struct CanvasSemanticsNode {
pub key: u64,
pub bounds: cranpose_ui_graphics::Rect,
pub label: String,
pub role: Option<SemanticsWidgetRole>,
pub state_description: Option<String>,
pub on_click_label: Option<String>,
pub clickable: bool,
pub selected: Option<bool>,
pub toggled: Option<ToggleableState>,
pub enabled: bool,
pub custom_actions: Vec<SemanticsCustomAction>,
}
impl Default for CanvasSemanticsNode {
fn default() -> Self {
Self {
key: 0,
bounds: cranpose_ui_graphics::Rect {
x: 0.0,
y: 0.0,
width: 0.0,
height: 0.0,
},
label: String::new(),
role: None,
state_description: None,
on_click_label: None,
clickable: false,
selected: None,
toggled: None,
enabled: true,
custom_actions: Vec::new(),
}
}
}
impl CanvasSemanticsNode {
pub fn control(key: u64, bounds: cranpose_ui_graphics::Rect, label: impl Into<String>) -> Self {
Self {
key,
bounds,
label: label.into(),
clickable: true,
..Self::default()
}
}
pub fn text(key: u64, bounds: cranpose_ui_graphics::Rect, label: impl Into<String>) -> Self {
Self {
key,
bounds,
label: label.into(),
..Self::default()
}
}
pub fn with_role(mut self, role: SemanticsWidgetRole) -> Self {
self.role = Some(role);
self
}
pub fn with_state_description(mut self, state: impl Into<String>) -> Self {
self.state_description = Some(state.into());
self
}
pub fn with_click_label(mut self, label: impl Into<String>) -> Self {
self.on_click_label = Some(label.into());
self.clickable = true;
self
}
pub fn with_selected(mut self, selected: bool) -> Self {
self.selected = Some(selected);
self
}
pub fn with_toggled(mut self, toggled: impl Into<ToggleableState>) -> Self {
self.toggled = Some(toggled.into());
self
}
pub fn with_enabled(mut self, enabled: bool) -> Self {
self.enabled = enabled;
self
}
pub fn with_custom_action(mut self, action: SemanticsCustomAction) -> Self {
self.custom_actions.push(action);
self
}
}
impl fmt::Debug for dyn ModifierNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ModifierNode").finish_non_exhaustive()
}
}
impl dyn ModifierNode {
pub fn as_any(&self) -> &dyn Any {
self
}
pub fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}
pub type ModifierInvalidations = smallvec::SmallVec<[ModifierInvalidation; 5]>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModifierInvalidation {
kind: InvalidationKind,
capabilities: NodeCapabilities,
}
impl ModifierInvalidation {
pub const fn new(kind: InvalidationKind, capabilities: NodeCapabilities) -> Self {
Self { kind, capabilities }
}
pub const fn kind(self) -> InvalidationKind {
self.kind
}
pub const fn capabilities(self) -> NodeCapabilities {
self.capabilities
}
}
#[cfg(test)]
#[path = "tests/modifier_tests.rs"]
mod tests;