use std::any::TypeId;
use accesskit::{Node, Role, Toggled};
use include_doc_path::include_doc_path;
use masonry_core::debug_panic;
use tracing::{Span, trace, trace_span};
use crate::core::{
AccessCtx, AccessEvent, ArcStr, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, NewWidget,
PaintCtx, PointerEvent, PrePaintProps, PropertiesMut, PropertiesRef, RegisterCtx, TextEvent,
Update, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut, WidgetPod, keyboard::Key,
paint_background, paint_box_shadow,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Cap, Circle, Dashes, Join, Point, Size, Stroke};
use crate::layout::{LayoutSize, LenReq, Length, SizeDef};
use crate::properties::{BorderColor, BorderWidth, CheckmarkColor, CheckmarkStrokeWidth};
use crate::theme;
use crate::widgets::{Label, RadioGroup};
#[doc = concat!(
",
")",
)]
pub struct RadioButton {
selected: bool,
label: WidgetPod<Label>,
parent_group: Option<WidgetId>,
}
impl RadioButton {
pub fn new(checked: bool, text: impl Into<ArcStr>) -> Self {
Self {
selected: checked,
label: WidgetPod::new(Label::new(text)),
parent_group: None,
}
}
pub fn from_label(checked: bool, label: NewWidget<Label>) -> Self {
Self {
selected: checked,
label: label.to_pod(),
parent_group: None,
}
}
}
impl RadioButton {
pub fn set_checked(this: &mut WidgetMut<'_, Self>, checked: bool) {
this.widget.selected = checked;
this.ctx.request_render();
let Some(parent_id) = this.widget.parent_group else {
return;
};
let self_id = this.ctx.widget_id();
this.ctx.mutate_later(parent_id, move |mut group| {
let group = group.downcast::<RadioGroup>();
Self::update_group(group, self_id, checked);
});
}
pub fn set_text(this: &mut WidgetMut<'_, Self>, new_text: ArcStr) {
Label::set_text(&mut Self::label_mut(this), new_text);
}
pub fn label_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, Label> {
this.ctx.get_mut(&mut this.widget.label)
}
}
impl UsesProperty<CheckmarkColor> for RadioButton {}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct RadioButtonSelected;
impl RadioButton {
fn select(&mut self, ctx: &mut EventCtx<'_>) {
self.selected = true;
ctx.submit_action::<RadioButtonSelected>(RadioButtonSelected);
ctx.request_render();
let Some(parent_id) = self.parent_group else {
return;
};
let self_id = ctx.widget_id();
ctx.mutate_later(parent_id, move |mut group| {
let group = group.downcast::<RadioGroup>();
Self::update_group(group, self_id, true);
});
}
fn update_group(mut group: WidgetMut<'_, RadioGroup>, self_id: WidgetId, selected: bool) {
let selected_button = group.widget.selected_button;
if let Some(button_id) = selected_button
&& button_id != self_id
&& selected
{
group.ctx.mutate_later(button_id, move |mut group| {
let mut button = group.downcast::<Self>();
button.widget.selected = false;
button.ctx.request_render();
});
}
if let Some(button_id) = selected_button
&& button_id == self_id
&& !selected
{
group.widget.selected_button = None;
}
if selected {
group.widget.selected_button = Some(self_id);
}
}
}
impl Widget for RadioButton {
type Action = RadioButtonSelected;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
match event {
PointerEvent::Down { .. } => {
ctx.capture_pointer();
trace!("RadioButton {:?} pressed", ctx.widget_id());
}
PointerEvent::Up { .. } if ctx.is_active() && ctx.is_hovered() => {
trace!("RadioButton {:?} released", ctx.widget_id());
self.select(ctx);
}
_ => (),
}
}
fn on_text_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &TextEvent,
) {
match event {
TextEvent::Keyboard(event) if event.state.is_up() => {
if matches!(&event.key, Key::Character(c) if c == " ") {
self.select(ctx);
}
}
_ => (),
}
}
fn accepts_focus(&self) -> bool {
true
}
fn on_access_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &AccessEvent,
) {
match event.action {
accesskit::Action::Click => {
self.select(ctx);
}
_ => {}
}
}
fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
match event {
Update::WidgetAdded => {
let Some((_, id)) = ctx.nearest_ancestor::<RadioGroup>() else {
let id = ctx.widget_id();
debug_panic!("RadioButton {id} is not a child of a RadioGroup");
return;
};
self.parent_group = Some(id);
}
Update::HoveredChanged(_)
| Update::ActiveChanged(_)
| Update::FocusChanged(_)
| Update::DisabledChanged(_) => {
ctx.request_paint_only();
}
_ => {}
}
}
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
ctx.register_child(&mut self.label);
}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
CheckmarkStrokeWidth::prop_changed(ctx, property_type);
CheckmarkColor::prop_changed(ctx, property_type);
}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
_props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
let check_side = theme::BASIC_WIDGET_HEIGHT;
let check_padding = theme::WIDGET_CONTROL_COMPONENT_PADDING;
let calc_other_length = |axis| match axis {
Axis::Horizontal => check_side.saturating_add(check_padding),
Axis::Vertical => Length::ZERO,
};
let other_length = calc_other_length(axis);
let cross = axis.cross();
let cross_space = cross_length.map(|cross_length| {
let cross_other_length = calc_other_length(cross);
cross_length.saturating_sub(cross_other_length)
});
let auto_length = len_req.reduce(other_length).into();
let context_size = LayoutSize::maybe(cross, cross_space);
let label_length = ctx.compute_length(
&mut self.label,
auto_length,
context_size,
axis,
cross_space,
);
match axis {
Axis::Horizontal => label_length.saturating_add(other_length),
Axis::Vertical => label_length.max(check_side).saturating_add(other_length),
}
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
let check_side = theme::BASIC_WIDGET_HEIGHT.get();
let check_padding = theme::WIDGET_CONTROL_COMPONENT_PADDING.get();
let space = Size::new(
(size.width - (check_side + check_padding)).max(0.),
size.height,
);
let label_size = ctx.compute_size(&mut self.label, SizeDef::fit(space), space.into());
ctx.run_layout(&mut self.label, label_size);
let label_origin = Point::new(check_side + check_padding, 0.);
ctx.place_child(&mut self.label, label_origin);
ctx.derive_baselines(&self.label);
}
fn pre_paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
let bbox = ctx.border_box();
let cache = ctx.property_cache();
let p = PrePaintProps::fetch(props, cache);
paint_box_shadow(painter, bbox, p.box_shadow, p.corner_radius);
paint_background(painter, bbox, p.background, p.border_width, p.corner_radius);
if ctx.is_focus_target() || ctx.is_hovered() {
let focus_rect = bbox.inflate(2.0, 2.0);
let focus_color = p.border_color.color;
let focus_width = 2.0;
let focus_radius = 4.0;
let focus_stroke = Stroke {
width: focus_width,
join: Join::Round,
miter_limit: 10.0,
start_cap: Cap::Round,
end_cap: Cap::Round,
dash_pattern: Dashes::default(),
dash_offset: 0.0,
};
let focus_path = focus_rect.to_rounded_rect(focus_radius);
painter
.stroke(focus_path, &focus_stroke, focus_color)
.draw();
}
}
fn paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
let cache = ctx.property_cache();
let border_color = *props.get::<BorderColor>(cache);
let border_width = *props.get::<BorderWidth>(cache);
let brush = *props.get::<CheckmarkColor>(cache);
let check_side = theme::BASIC_WIDGET_HEIGHT.get();
let check_size = Size::new(check_side, check_side);
let border_circle = Circle::new(
check_size.to_rect().center(),
(check_side - border_width.width.get()) * 0.5,
);
let border_stroke = Stroke::new(border_width.width.get());
painter
.stroke(border_circle, &border_stroke, border_color.color)
.draw();
if self.selected {
let check_circle = Circle::new(check_size.to_rect().center(), check_side * 0.25);
painter.fill(check_circle, brush.color).draw();
}
}
fn accessibility_role(&self) -> Role {
Role::RadioButton
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut Node,
) {
node.add_action(accesskit::Action::Click);
if self.selected {
node.set_toggled(Toggled::True);
} else {
node.set_toggled(Toggled::False);
}
}
fn children_ids(&self) -> ChildrenIds {
ChildrenIds::from_slice(&[self.label.id()])
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("RadioButton", id = id.trace())
}
fn get_debug_text(&self) -> Option<String> {
if self.selected {
Some("(X)".to_string())
} else {
Some("( )".to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{StyleProperty, WidgetTag};
use crate::properties::ContentColor;
use crate::testing::{TestHarness, assert_render_snapshot};
use crate::theme::{ACCENT_COLOR, default_property_set};
use crate::widgets::Flex;
#[test]
fn simple_radio_button() {
let radio_tag = WidgetTag::unique();
let widget = NewWidget::new(RadioButton::new(false, "Hello")).with_tag(radio_tag);
let widget = NewWidget::new(RadioGroup::new(widget));
let mut harness = TestHarness::create_with_size(default_property_set(), widget, (100, 40));
let radio_id = harness.get_widget(radio_tag).id();
assert_render_snapshot!(harness, "radio_button_hello_unchecked");
assert!(harness.pop_action_erased().is_none());
harness.mouse_move_to(radio_tag);
assert_render_snapshot!(harness, "radio_button_hello_hovered");
harness.mouse_click_on(radio_tag, None);
assert_eq!(
harness.pop_action::<RadioButtonSelected>(),
Some((RadioButtonSelected, radio_id))
);
assert_render_snapshot!(harness, "radio_button_hello_checked");
harness.edit_root_widget(|mut group| {
let mut radio = RadioGroup::child_mut(&mut group);
let mut radio = radio.downcast();
RadioButton::set_checked(&mut radio, false);
});
assert_render_snapshot!(harness, "radio_button_hello_hovered");
harness.clear_focus();
harness.press_tab_key(false);
assert_eq!(harness.focused_widget().map(|w| w.id()), Some(radio_id));
}
#[test]
fn radio_button_focus_indicator() {
use crate::properties::types::MainAxisAlignment;
let radio_tag = WidgetTag::unique();
let radio = NewWidget::new(RadioButton::new(true, "Focus test")).with_tag(radio_tag);
let group = NewWidget::new(RadioGroup::new(radio));
let root = NewWidget::new(
Flex::row()
.with_fixed(group)
.main_axis_alignment(MainAxisAlignment::Center),
);
let mut harness = TestHarness::create_with_size(default_property_set(), root, (120, 40));
harness.focus_on(radio_tag);
assert_render_snapshot!(harness, "radio_button_focus_focused");
}
#[test]
fn edit_radio_button() {
let image_1 = {
let label = Label::new("The quick brown fox jumps over the lazy dog")
.with_style(StyleProperty::FontSize(20.0));
let label = NewWidget::new(label).with_props(ContentColor::new(ACCENT_COLOR));
let radio = NewWidget::new(RadioButton::from_label(true, label));
let group = NewWidget::new(RadioGroup::new(radio));
let mut harness =
TestHarness::create_with_size(default_property_set(), group, (50, 50));
harness.render()
};
let image_2 = {
let radio = NewWidget::new(RadioButton::new(false, "Hello world"));
let group = NewWidget::new(RadioGroup::new(radio));
let mut harness =
TestHarness::create_with_size(default_property_set(), group, (50, 50));
harness.edit_root_widget(|mut group| {
let mut radio = RadioGroup::child_mut(&mut group);
let mut radio = radio.downcast();
RadioButton::set_checked(&mut radio, true);
RadioButton::set_text(
&mut radio,
ArcStr::from("The quick brown fox jumps over the lazy dog"),
);
let mut label = RadioButton::label_mut(&mut radio);
label.insert_prop(ContentColor::new(ACCENT_COLOR));
Label::insert_style(&mut label, StyleProperty::FontSize(20.0));
});
harness.render()
};
assert!(image_1 == image_2);
}
}