use accesskit::{Node, Role};
use tracing::{Span, trace_span};
use crate::core::{
AccessCtx, AccessEvent, ChildrenIds, CollectionWidget, ComposeCtx, EventCtx, LayoutCtx,
MeasureCtx, NewWidget, NoAction, PaintCtx, PointerButton, PointerButtonEvent, PointerEvent,
PropertiesMut, PropertiesRef, RegisterCtx, Subwindow, TextEvent, Update, UpdateCtx,
UsesProperty, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size};
use crate::layout::{AsUnit, LayoutSize, LenDef, LenReq, Length, SizeDef};
use crate::properties::Gap;
use crate::widgets::{SelectionChanged, Selector};
pub struct SelectorMenu {
creator: WidgetId,
children: Vec<WidgetPod<dyn Widget>>,
}
impl SelectorMenu {
pub fn new(creator: WidgetId) -> Self {
Self {
creator,
children: Vec::new(),
}
}
pub fn with(mut self, child: NewWidget<impl Widget + ?Sized>) -> Self {
let child = child.erased().to_pod();
self.children.push(child);
self
}
}
impl CollectionWidget<()> for SelectorMenu {
fn len(&self) -> usize {
self.children.len()
}
fn is_empty(&self) -> bool {
self.children.is_empty()
}
fn get_mut<'t>(this: &'t mut WidgetMut<'_, Self>, idx: usize) -> WidgetMut<'t, dyn Widget> {
let child = &mut this.widget.children[idx];
this.ctx.get_mut(child)
}
fn add(
this: &mut WidgetMut<'_, Self>,
child: NewWidget<impl Widget + ?Sized>,
_params: impl Into<()>,
) {
let child = child.erased().to_pod();
this.widget.children.push(child);
this.ctx.children_changed();
}
fn insert(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
_params: impl Into<()>,
) {
let child = child.erased().to_pod();
this.widget.children.insert(idx, child);
this.ctx.children_changed();
}
fn set(
this: &mut WidgetMut<'_, Self>,
idx: usize,
child: NewWidget<impl Widget + ?Sized>,
_params: impl Into<()>,
) {
let child = child.erased().to_pod();
let old_child = std::mem::replace(&mut this.widget.children[idx], child);
this.ctx.remove_child(old_child);
}
fn set_params(_this: &mut WidgetMut<'_, Self>, _idx: usize, _params: impl Into<()>) {}
fn swap(this: &mut WidgetMut<'_, Self>, a: usize, b: usize) {
this.widget.children.swap(a, b);
this.ctx.children_changed();
}
fn remove(this: &mut WidgetMut<'_, Self>, idx: usize) {
let child = this.widget.children.remove(idx);
this.ctx.remove_child(child);
}
fn clear(this: &mut WidgetMut<'_, Self>) {
for child in this.widget.children.drain(..) {
this.ctx.remove_child(child);
}
}
}
impl UsesProperty<Gap> for SelectorMenu {}
impl Widget for SelectorMenu {
type Action = NoAction;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
match event {
PointerEvent::Up(PointerButtonEvent {
button: None | Some(PointerButton::Primary),
..
}) => {
let self_id = ctx.subwindow_id().unwrap();
let clicked_id = ctx.target();
let index = self
.children
.iter()
.position(|child| child.id() == clicked_id)
.unwrap();
ctx.mutate_later(self.creator, move |mut selector| {
let mut selector = selector.downcast::<Selector>();
let selected_content = selector.widget.options[index].clone();
if selector.ctx.get_attached_subwindow::<Self>().is_none() {
return;
}
let action = SelectionChanged {
selected_content,
index,
};
selector.ctx.submit_action::<SelectionChanged>(action);
selector.ctx.remove_subwindow(self_id);
Selector::select_option(&mut selector, index);
});
}
_ => (),
}
}
fn on_text_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &TextEvent,
) {
match event {
TextEvent::WindowFocusChange(false) => {
ctx.remove_subwindow(ctx.subwindow_id().unwrap());
}
_ => (),
}
}
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 update(
&mut self,
_ctx: &mut UpdateCtx<'_>,
_props: &mut PropertiesMut<'_>,
_event: &Update,
) {
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
let cache = ctx.property_cache();
let gap = props.get::<Gap>(cache);
let gap_length = gap.gap.get();
let (len_req, min_result) = match len_req {
LenReq::MinContent | LenReq::MaxContent => (len_req, Length::ZERO),
LenReq::FitContent(space) => (LenReq::MinContent, space),
};
let auto_length = len_req.into();
let context_size = LayoutSize::maybe(axis.cross(), cross_length);
let mut length = Length::ZERO;
for child in &mut self.children {
let child_length =
ctx.compute_length(child, auto_length, context_size, axis, cross_length);
match axis {
Axis::Horizontal => length = length.max(child_length),
Axis::Vertical => length = length.saturating_add(child_length),
}
}
if axis == Axis::Vertical {
let gap_count = (self.children.len() - 1) as f64;
let gaps_length = gap_count * gap_length;
length = length.saturating_add(gaps_length.px());
}
min_result.max(length)
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, props: &PropertiesRef<'_>, size: Size) {
let cache = ctx.property_cache();
let gap = props.get::<Gap>(cache);
let gap_count = (self.children.len() - 1) as f64;
let gap_length = gap.gap.get();
let total_child_vertical_space = size.height - gap_length * gap_count;
let child_vertical_space = total_child_vertical_space / self.children.len() as f64;
let width_def = LenDef::FitContent(size.width.px());
let height_def = LenDef::FitContent(child_vertical_space.max(0.).px());
let auto_size = SizeDef::new(width_def, height_def);
let context_size = size.into();
let mut y_offset = 0.0;
for child in &mut self.children {
let mut child_size = ctx.compute_size(child, auto_size, context_size);
child_size.width = size.width;
ctx.run_layout(child, child_size);
ctx.place_child(child, Point::new(0.0, y_offset));
y_offset += child_size.height + gap_length;
}
if !self.children.is_empty() {
let first_child = self.children.first().unwrap();
let (first_baseline, _) = ctx.child_aligned_baselines(first_child);
let first_child_origin = ctx.child_origin(first_child);
let first_baseline = first_child_origin.y + first_baseline;
let last_child = self.children.last().unwrap();
let (_, last_baseline) = ctx.child_aligned_baselines(last_child);
let last_child_origin = ctx.child_origin(last_child);
let last_baseline = last_child_origin.y + last_baseline;
ctx.set_baselines(first_baseline, last_baseline);
} else {
ctx.clear_baselines();
}
}
fn compose(&mut self, _ctx: &mut ComposeCtx<'_>) {}
fn paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
}
fn accessibility_role(&self) -> Role {
Role::GenericContainer
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
_node: &mut Node,
) {
}
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
for child in &mut self.children {
ctx.register_child(child);
}
}
fn children_ids(&self) -> ChildrenIds {
self.children.iter().map(|child| child.id()).collect()
}
fn as_subwindow(&mut self) -> Option<&mut dyn Subwindow> {
Some(self)
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("SelectorMenu", id = id.trace())
}
}
impl Subwindow for SelectorMenu {
fn capture_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
let remove_this = match event {
PointerEvent::Down(PointerButtonEvent { state, .. }) => {
let local_pos = ctx.local_position(state.position);
!ctx.border_box().contains(local_pos)
}
PointerEvent::Cancel(..) => true,
_ => false,
};
if remove_this {
ctx.remove_subwindow(ctx.subwindow_id().unwrap());
}
}
}