use std::any::TypeId;
use accesskit::{Node, Role, Toggled};
use include_doc_path::include_doc_path;
use tracing::{Span, trace, trace_span};
use crate::core::keyboard::Key;
use crate::core::{
AccessCtx, AccessEvent, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, PaintCtx, PointerEvent,
PropertiesMut, PropertiesRef, RegisterCtx, TextEvent, Update, UpdateCtx, UsesProperty, Widget,
WidgetId, WidgetMut,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Circle, Join, Point, Rect, Size, Stroke};
use crate::layout::{LenReq, Length};
use crate::properties::{
Background, BorderColor, BorderWidth, CornerRadius, ThumbColor, ThumbRadius, TrackThickness,
};
#[doc = concat!(
",
")",
)]
pub struct Switch {
on: bool,
}
impl Switch {
pub fn new(on: bool) -> Self {
Self { on }
}
pub fn is_on(&self) -> bool {
self.on
}
}
impl Switch {
pub fn set_on(this: &mut WidgetMut<'_, Self>, on: bool) {
this.widget.on = on;
if on {
this.ctx.add_class("#toggled");
} else {
this.ctx.remove_class("#toggled");
}
}
}
impl Switch {
fn track_dimensions(track_thickness: Length, thumb_radius: Length) -> (Length, Length) {
let track_height = track_thickness.max(thumb_radius.saturating_add(thumb_radius));
let track_width = track_height.saturating_add(track_height);
(track_width, track_height)
}
}
impl UsesProperty<ThumbRadius> for Switch {}
impl UsesProperty<ThumbColor> for Switch {}
impl UsesProperty<TrackThickness> for Switch {}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct SwitchToggled(pub bool);
impl Widget for Switch {
type Action = SwitchToggled;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
match event {
PointerEvent::Down { .. } => {
ctx.request_focus();
ctx.capture_pointer();
trace!("Switch {:?} pressed", ctx.widget_id());
}
PointerEvent::Up { .. } if ctx.is_active() && ctx.is_hovered() => {
ctx.submit_action::<Self::Action>(SwitchToggled(!self.on));
trace!("Switch {:?} released", ctx.widget_id());
}
_ => (),
}
}
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 == " ") {
ctx.submit_action::<Self::Action>(SwitchToggled(!self.on));
ctx.set_handled();
}
}
_ => (),
}
}
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 => {
ctx.submit_action::<Self::Action>(SwitchToggled(!self.on));
}
_ => {}
}
}
fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
match event {
Update::WidgetAdded if self.on => {
ctx.add_class("#toggled");
}
Update::HoveredChanged(_)
| Update::ActiveChanged(_)
| Update::FocusChanged(_)
| Update::DisabledChanged(_) => {
ctx.request_paint_only();
}
_ => {}
}
}
fn register_children(&mut self, _ctx: &mut RegisterCtx<'_>) {}
fn property_changed(&mut self, ctx: &mut UpdateCtx<'_>, property_type: TypeId) {
ThumbRadius::prop_changed(ctx, property_type);
ThumbColor::prop_changed(ctx, property_type);
TrackThickness::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 cache = ctx.property_cache();
let track_thickness = props.get::<TrackThickness>(cache).0;
let thumb_radius = props.get::<ThumbRadius>(cache).0;
let (track_width, track_height) = Self::track_dimensions(track_thickness, thumb_radius);
match axis {
Axis::Horizontal => track_width,
Axis::Vertical => track_height,
}
}
fn layout(&mut self, _ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, _size: Size) {}
fn pre_paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
}
fn paint(
&mut self,
ctx: &mut PaintCtx<'_>,
props: &PropertiesRef<'_>,
painter: &mut Painter<'_>,
) {
let is_disabled = ctx.is_disabled();
let size = ctx.border_box().size();
let border_box_translation = ctx.border_box_translation();
let cache = ctx.property_cache();
let track_thickness_val = props.get::<TrackThickness>(cache).0;
let thumb_radius_val = props.get::<ThumbRadius>(cache).0;
let (track_width, track_height) =
Self::track_dimensions(track_thickness_val, thumb_radius_val);
let track_width = track_width.get();
let track_height = track_height.get();
let thumb_radius = thumb_radius_val.get();
let border_width = props.get::<BorderWidth>(cache).width.get();
let corner_radius = props.get::<CornerRadius>(cache).radius.get();
let thumb_color = props.get::<ThumbColor>(cache).0;
let track_x = (size.width - track_width) / 2.0;
let track_y = (size.height - track_height) / 2.0;
let track_rect = Rect::new(
track_x,
track_y,
track_x + track_width,
track_y + track_height,
) - border_box_translation;
let track_bg = props.get::<Background>(cache);
let track_corner_radius = corner_radius.min(track_height / 2.0);
let track_rounded = track_rect.to_rounded_rect(track_corner_radius);
let brush = track_bg.get_peniko_brush_for_rect(track_rect);
painter.fill(track_rounded, &brush).draw();
let border_color = props.get::<BorderColor>(cache);
if border_width > 0.0 {
let stroke = Stroke::new(border_width).with_join(Join::Miter);
painter
.stroke(track_rounded, &stroke, border_color.color)
.draw();
}
let thumb_y = size.height / 2.0 - border_box_translation.y;
let thumb_x = if self.on {
track_rect.x1 - thumb_radius - border_width / 2.0
} else {
track_rect.x0 + thumb_radius + border_width / 2.0
};
let thumb_circle = Circle::new(Point::new(thumb_x, thumb_y), thumb_radius);
let thumb_brush = if is_disabled {
thumb_color.with_alpha(0.5)
} else {
thumb_color
};
painter.fill(thumb_circle, thumb_brush).draw();
}
fn accessibility_role(&self) -> Role {
Role::Switch
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut Node,
) {
node.add_action(accesskit::Action::Click);
if self.on {
node.set_toggled(Toggled::True);
} else {
node.set_toggled(Toggled::False);
}
}
fn children_ids(&self) -> ChildrenIds {
ChildrenIds::new()
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Switch", id = id.trace())
}
fn get_debug_text(&self) -> Option<String> {
if self.on {
Some("[ON]".to_string())
} else {
Some("[OFF]".to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::TextEvent;
use crate::properties::types::{CrossAxisAlignment, MainAxisAlignment};
use crate::testing::{TestHarness, assert_render_snapshot};
use crate::theme::test_property_set;
use crate::widgets::Flex;
#[test]
fn click_emits_action_and_focuses() {
let widget = Switch::new(false).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
let switch_id = harness.root_id();
let switch_tag = harness.root_tag();
assert!(harness.focused_widget().is_none());
assert!(harness.pop_action_erased().is_none());
harness.mouse_click_on(switch_tag, None);
assert_eq!(harness.focused_widget().map(|w| w.id()), Some(switch_id));
assert_eq!(
harness.pop_action::<SwitchToggled>(),
Some((SwitchToggled(true), switch_id))
);
harness.edit_root_widget(|mut switch| Switch::set_on(&mut switch, true));
harness.mouse_click_on(switch_tag, None);
assert_eq!(
harness.pop_action::<SwitchToggled>(),
Some((SwitchToggled(false), switch_id))
);
}
#[test]
fn space_emits_action_when_focused() {
let widget = Switch::new(false).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
let switch_id = harness.root_id();
harness.clear_focus();
harness.press_tab_key(false);
assert_eq!(harness.focused_widget().map(|w| w.id()), Some(switch_id));
harness.process_text_event(TextEvent::key_down(Key::Character(" ".into())));
harness.process_text_event(TextEvent::key_up(Key::Character(" ".into())));
assert_eq!(
harness.pop_action::<SwitchToggled>(),
Some((SwitchToggled(true), switch_id))
);
harness.edit_root_widget(|mut switch| Switch::set_on(&mut switch, true));
harness.process_text_event(TextEvent::key_down(Key::Character(" ".into())));
harness.process_text_event(TextEvent::key_up(Key::Character(" ".into())));
assert_eq!(
harness.pop_action::<SwitchToggled>(),
Some((SwitchToggled(false), switch_id))
);
}
#[test]
fn measure_dimensions() {
let switch = Switch::new(false).prepare();
let switch_id = switch.id();
let flex = Flex::row()
.with_fixed(switch)
.main_axis_alignment(MainAxisAlignment::Start)
.cross_axis_alignment(CrossAxisAlignment::Start);
let harness =
TestHarness::create_with_size(test_property_set(), flex.prepare(), (200, 100));
let size = harness
.get_widget_with_id(switch_id)
.ctx()
.border_box()
.size();
assert_eq!(
size.width, 42.0,
"Switch width should be 2*track_height + 2*border"
);
assert_eq!(
size.height, 22.0,
"Switch height should be track_height + 2*border"
);
}
#[test]
fn simple_switch() {
let widget = Switch::new(false).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
let switch_id = harness.root_id();
let switch_tag = harness.root_tag();
assert_render_snapshot!(harness, "switch_off");
assert!(harness.pop_action_erased().is_none());
harness.mouse_move_to(switch_tag);
assert_render_snapshot!(harness, "switch_off_hovered");
harness.mouse_click_on(switch_tag, None);
assert_eq!(
harness.pop_action::<SwitchToggled>(),
Some((SwitchToggled(true), switch_id))
);
harness.edit_root_widget(|mut switch| Switch::set_on(&mut switch, true));
assert_render_snapshot!(harness, "switch_on_focused_hovered");
}
#[test]
fn focus_visual() {
let widget = Switch::new(false).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
let switch_tag = harness.root_tag();
let switch_id = harness.root_id();
harness.focus_on(switch_tag);
assert_eq!(harness.focused_widget().map(|w| w.id()), Some(switch_id));
assert_render_snapshot!(harness, "switch_focused");
}
#[test]
fn on_state() {
let widget = Switch::new(true).prepare();
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (60, 40));
assert_render_snapshot!(harness, "switch_on_initial");
}
}