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, ArcStr, ChildrenIds, EventCtx, LayoutCtx, MeasureCtx, NewWidget,
PaintCtx, PointerEvent, PrePaintProps, PropertiesMut, PropertiesRef, Property, RegisterCtx,
TextEvent, Update, UpdateCtx, UsesProperty, Widget, WidgetId, WidgetMut, WidgetPod,
paint_background, paint_box_shadow,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, BezPath, Cap, Dashes, Join, Point, Size, Stroke};
use crate::layout::{LayoutSize, LenReq, Length, SizeDef};
use crate::properties::{
BorderColor, BorderWidth, CheckmarkColor, CheckmarkStrokeWidth, CornerRadius,
};
use crate::theme;
use crate::widgets::Label;
#[doc = concat!(
",
")",
)]
pub struct Checkbox {
checked: bool,
label: WidgetPod<Label>,
}
impl Checkbox {
pub fn new(checked: bool, text: impl Into<ArcStr>) -> Self {
Self {
checked,
label: WidgetPod::new(Label::new(text)),
}
}
pub fn from_label(checked: bool, label: NewWidget<Label>) -> Self {
Self {
checked,
label: label.to_pod(),
}
}
}
impl Checkbox {
pub fn set_checked(this: &mut WidgetMut<'_, Self>, checked: bool) {
this.widget.checked = checked;
this.ctx.request_render();
}
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<CheckmarkStrokeWidth> for Checkbox {}
impl UsesProperty<CheckmarkColor> for Checkbox {}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct CheckboxToggled(pub bool);
impl Widget for Checkbox {
type Action = CheckboxToggled;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
match event {
PointerEvent::Down { .. } => {
ctx.capture_pointer();
trace!("Checkbox {:?} pressed", ctx.widget_id());
}
PointerEvent::Up { .. } if ctx.is_active() && ctx.is_hovered() => {
ctx.submit_action::<Self::Action>(CheckboxToggled(!self.checked));
trace!("Checkbox {:?} 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>(CheckboxToggled(!self.checked));
}
}
_ => (),
}
}
fn propagates_pointer_interaction(&self) -> bool {
false
}
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>(CheckboxToggled(!self.checked));
}
_ => {}
}
}
fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
match event {
Update::HoveredChanged(_) | 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) {
if BorderWidth::matches(property_type) {
ctx.request_layout();
}
if CornerRadius::matches(property_type)
|| BorderColor::matches(property_type)
|| CheckmarkStrokeWidth::matches(property_type)
|| CheckmarkColor::matches(property_type)
{
ctx.request_paint_only();
}
}
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 check_side = theme::BASIC_WIDGET_HEIGHT.get();
let check_size = Size::new(check_side, check_side);
let cache = ctx.property_cache();
let border_width = *props.get::<BorderWidth>(cache);
let border_radius = *props.get::<CornerRadius>(cache);
let border_rect = border_width.border_rect(check_size.to_rect(), &border_radius);
let border_color = *props.get::<BorderColor>(cache);
let border_stroke = Stroke::new(border_width.width.get()).with_join(Join::Miter);
painter
.stroke(border_rect, &border_stroke, border_color.color)
.draw();
if self.checked {
let checkmark_width = *props.get::<CheckmarkStrokeWidth>(cache);
let brush = *props.get::<CheckmarkColor>(cache);
let mut path = BezPath::new();
path.move_to((4.0, 9.0));
path.line_to((8.0, 13.0));
path.line_to((14.0, 5.0));
let style = Stroke {
width: checkmark_width.width,
join: Join::Round,
miter_limit: 10.0,
start_cap: Cap::Round,
end_cap: Cap::Round,
dash_pattern: Dashes::default(),
dash_offset: 0.0,
};
painter.stroke(path, &style, brush.color).draw();
}
}
fn accessibility_role(&self) -> Role {
Role::CheckBox
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut Node,
) {
node.add_action(accesskit::Action::Click);
if self.checked {
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!("Checkbox", id = id.trace())
}
fn get_debug_text(&self) -> Option<String> {
if self.checked {
Some("[X]".to_string())
} else {
Some("[ ]".to_string())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{PropertySet, StyleProperty, WidgetTag};
use crate::layout::AsUnit;
use crate::properties::{ContentColor, Padding};
use crate::testing::{TestHarness, TestHarnessParams, assert_render_snapshot};
use crate::theme::{ACCENT_COLOR, test_property_set};
use crate::widgets::Flex;
#[test]
fn simple_checkbox() {
let widget = NewWidget::new(Checkbox::new(false, "Hello"));
let mut harness = TestHarness::create_with_size(test_property_set(), widget, (100, 40));
let checkbox_tag = harness.root_tag();
let checkbox_id = harness.root_id();
assert_render_snapshot!(harness, "checkbox_hello_unchecked");
assert!(harness.pop_action_erased().is_none());
harness.mouse_click_on(checkbox_tag, None);
assert_eq!(
harness.pop_action::<CheckboxToggled>(),
Some((CheckboxToggled(true), checkbox_id))
);
assert_render_snapshot!(harness, "checkbox_hello_hovered");
harness.edit_root_widget(|mut checkbox| Checkbox::set_checked(&mut checkbox, true));
assert_render_snapshot!(harness, "checkbox_hello_checked");
harness.clear_focus();
harness.press_tab_key(false);
assert_eq!(harness.focused_widget().map(|w| w.id()), Some(checkbox_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::<CheckboxToggled>(),
Some((CheckboxToggled(false), checkbox_id))
);
}
#[test]
fn checkbox_focus_indicator() {
use crate::properties::types::MainAxisAlignment;
let checkbox_tag = WidgetTag::named("checkbox");
let checkbox = NewWidget::new(Checkbox::new(true, "Focus test")).with_tag(checkbox_tag);
let root = NewWidget::new(
Flex::row()
.with_fixed(checkbox)
.main_axis_alignment(MainAxisAlignment::Center),
);
let mut harness = TestHarness::create_with_size(test_property_set(), root, (120, 40));
harness.focus_on(checkbox_tag);
assert_render_snapshot!(harness, "checkbox_focus_focused");
}
#[test]
fn checkbox_with_padding() {
let checkbox_tag = WidgetTag::named("checkbox");
let checkbox = NewWidget::new(Checkbox::new(true, "Padding"))
.with_tag(checkbox_tag)
.with_props(Padding::from_vh(8.px(), 16.px()));
let params =
TestHarnessParams::size_and_padding((180, 72), TestHarnessParams::ROOT_PADDING);
let mut harness = TestHarness::create_with(test_property_set(), checkbox, params);
harness.focus_on(checkbox_tag);
assert_render_snapshot!(harness, "checkbox_with_padding_focused");
}
#[test]
fn edit_checkbox() {
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(PropertySet::new().with(ContentColor::new(ACCENT_COLOR)));
let checkbox = NewWidget::new(Checkbox::from_label(true, label));
let mut harness =
TestHarness::create_with_size(test_property_set(), checkbox, (50, 50));
harness.render()
};
let image_2 = {
let checkbox = NewWidget::new(Checkbox::new(false, "Hello world"));
let mut harness =
TestHarness::create_with_size(test_property_set(), checkbox, (50, 50));
harness.edit_root_widget(|mut checkbox| {
Checkbox::set_checked(&mut checkbox, true);
Checkbox::set_text(
&mut checkbox,
ArcStr::from("The quick brown fox jumps over the lazy dog"),
);
let mut label = Checkbox::label_mut(&mut checkbox);
label.insert_prop(ContentColor::new(ACCENT_COLOR));
Label::insert_style(&mut label, StyleProperty::FontSize(20.0));
});
harness.render()
};
assert!(image_1 == image_2);
}
}