use std::any::TypeId;
use std::sync::Arc;
use accesskit::{Node, Role};
use include_doc_path::include_doc_path;
use tracing::{Span, trace, trace_span};
use crate::core::MeasureCtx;
use crate::core::keyboard::{Key, NamedKey};
use crate::core::pointer::PointerButton;
use crate::core::{
AccessCtx, AccessEvent, ArcStr, ChildrenIds, EventCtx, LayoutCtx, NewWidget, PaintCtx,
PointerButtonEvent, PointerEvent, PropertiesMut, PropertiesRef, RegisterCtx, SubwindowType,
TextEvent, Update, UpdateCtx, Widget, WidgetId, WidgetMut, WidgetPod,
};
use crate::imaging::Painter;
use crate::kurbo::{Axis, Point, Size, Vec2};
use crate::layout::{LayoutSize, LenReq, Length, SizeDef};
use crate::subwindows::Tooltip;
use crate::theme;
use crate::widgets::Label;
#[doc = concat!(
",
")",
)]
pub struct Button {
child: WidgetPod<dyn Widget>,
tooltip_text: Option<ArcStr>,
}
impl Button {
pub fn new(child: NewWidget<impl Widget + ?Sized>) -> Self {
Self {
child: child.erased().to_pod(),
tooltip_text: None,
}
}
pub fn with_text(text: impl Into<Arc<str>>) -> Self {
Self::new(Label::new(text).prepare())
}
pub fn with_tooltip(mut self, text: impl Into<Arc<str>>) -> Self {
self.tooltip_text = Some(text.into());
self
}
}
impl Button {
pub fn set_child(this: &mut WidgetMut<'_, Self>, child: NewWidget<impl Widget + ?Sized>) {
this.ctx.remove_child(std::mem::replace(
&mut this.widget.child,
child.erased().to_pod(),
));
}
pub fn child_mut<'t>(this: &'t mut WidgetMut<'_, Self>) -> WidgetMut<'t, dyn Widget> {
this.ctx.get_mut(&mut this.widget.child)
}
pub fn set_tooltip(this: &mut WidgetMut<'_, Self>, text: Option<impl Into<Arc<str>>>) {
this.widget.tooltip_text = text.map(Into::into);
}
}
#[derive(PartialEq, Debug)]
pub struct ButtonPress {
pub button: Option<PointerButton>,
}
impl Widget for Button {
type Action = ButtonPress;
fn on_pointer_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &PointerEvent,
) {
match event {
PointerEvent::Down(..) => {
ctx.request_focus();
ctx.capture_pointer();
ctx.request_paint_only();
trace!("Button {:?} pressed", ctx.widget_id());
}
PointerEvent::Up(PointerButtonEvent { button, .. }) => {
if ctx.is_active() && ctx.is_hovered() {
ctx.submit_action::<Self::Action>(ButtonPress { button: *button });
trace!("Button {:?} released", ctx.widget_id());
}
ctx.request_paint_only();
}
_ => (),
}
}
fn on_text_event(
&mut self,
ctx: &mut EventCtx<'_>,
_props: &mut PropertiesMut<'_>,
event: &TextEvent,
) {
match event {
TextEvent::Keyboard(event)
if event.state.is_up()
&& (matches!(&event.key, Key::Character(c) if c == " ")
|| event.key == Key::Named(NamedKey::Enter)) =>
{
ctx.submit_action::<Self::Action>(ButtonPress { button: None });
}
_ => (),
}
}
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>(ButtonPress { button: None });
}
_ => {}
}
}
fn update(&mut self, ctx: &mut UpdateCtx<'_>, _props: &mut PropertiesMut<'_>, event: &Update) {
match event {
Update::TooltipRequested(pos) => {
let Some(text) = &self.tooltip_text else {
return;
};
let tooltip_widget = Tooltip::with_text(text.clone()).prepare();
let pos = Point::new(pos.x, pos.y) + Vec2::new(5., -25.);
ctx.create_attached_subwindow(
SubwindowType::Tooltip(text.to_string()),
tooltip_widget,
pos,
);
}
_ => {}
}
}
fn register_children(&mut self, ctx: &mut RegisterCtx<'_>) {
ctx.register_child(&mut self.child);
}
fn property_changed(&mut self, _ctx: &mut UpdateCtx<'_>, _property_type: TypeId) {}
fn measure(
&mut self,
ctx: &mut MeasureCtx<'_>,
_props: &PropertiesRef<'_>,
axis: Axis,
len_req: LenReq,
cross_length: Option<Length>,
) -> Length {
let auto_length = len_req.into();
let context_size = LayoutSize::maybe(axis.cross(), cross_length);
let child_length = ctx.compute_length(
&mut self.child,
auto_length,
context_size,
axis,
cross_length,
);
let length = child_length;
match axis {
Axis::Horizontal => length,
Axis::Vertical => length.max(theme::BASIC_WIDGET_HEIGHT),
}
}
fn layout(&mut self, ctx: &mut LayoutCtx<'_>, _props: &PropertiesRef<'_>, size: Size) {
let child_size = ctx.compute_size(&mut self.child, SizeDef::fit(size), size.into());
ctx.run_layout(&mut self.child, child_size);
let child_origin = ((size - child_size).to_vec2() * 0.5).to_point();
ctx.place_child(&mut self.child, child_origin);
ctx.derive_baselines(&self.child);
}
fn paint(
&mut self,
_ctx: &mut PaintCtx<'_>,
_props: &PropertiesRef<'_>,
_painter: &mut Painter<'_>,
) {
}
fn accessibility_role(&self) -> Role {
Role::Button
}
fn accessibility(
&mut self,
_ctx: &mut AccessCtx<'_>,
_props: &PropertiesRef<'_>,
node: &mut Node,
) {
node.add_action(accesskit::Action::Click);
}
fn children_ids(&self) -> ChildrenIds {
ChildrenIds::from_slice(&[self.child.id()])
}
fn propagates_pointer_interaction(&self) -> bool {
false
}
fn accepts_tooltips(&self) -> bool {
true
}
fn accepts_focus(&self) -> bool {
true
}
fn accepts_text_input(&self) -> bool {
false
}
fn make_trace_span(&self, id: WidgetId) -> Span {
trace_span!("Button", id = id.trace())
}
}
#[cfg(test)]
mod tests {
use std::assert_matches;
use super::*;
use crate::core::{CollectionWidget, PointerButton, PropertySet, StyleProperty, WidgetTag};
use crate::layout::AsUnit;
use crate::properties::{
BorderColor, BorderWidth, BoxShadow, ContentColor, CornerRadius, Gap, Padding,
};
use crate::testing::{
TestHarness, TestHarnessParams, assert_failing_render_snapshot, assert_render_snapshot,
};
use crate::theme::{ACCENT_COLOR, test_property_set};
use crate::widgets::{Flex, Grid, GridParams, Label, SizedBox};
#[test]
fn simple_button() {
let widget = NewWidget::new(Button::with_text("Hello"));
let params =
TestHarnessParams::size_and_padding((100, 40), TestHarnessParams::ROOT_PADDING);
let mut harness = TestHarness::create_with(test_property_set(), widget, params);
let button_tag = harness.root_tag();
let button_id = harness.root_id();
assert_render_snapshot!(harness, "button_hello");
assert!(harness.pop_action_erased().is_none());
harness.mouse_click_on(button_tag, Some(PointerButton::Primary));
assert_eq!(
harness.pop_action::<ButtonPress>(),
Some((
ButtonPress {
button: Some(PointerButton::Primary)
},
button_id
))
);
harness.clear_focus();
harness.press_tab_key(false);
assert_eq!(harness.focused_widget().map(|w| w.id()), Some(button_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(),
Some((ButtonPress { button: None }, button_id))
);
}
#[test]
fn mouse_down_requests_focus() {
let widget = NewWidget::new(Button::with_text("Hello"));
let mut harness = TestHarness::create(test_property_set(), widget);
let button_tag = harness.root_tag();
let button_id = harness.root_id();
harness.clear_focus();
harness.mouse_move_to(button_tag);
harness.mouse_button_press(None);
assert_eq!(harness.focused_widget_id(), Some(button_id));
}
#[test]
fn edit_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(PropertySet::new().with(ContentColor::new(ACCENT_COLOR)));
let button = NewWidget::new(Button::new(label));
let mut harness = TestHarness::create_with_size(test_property_set(), button, (50, 50));
harness.render()
};
let image_2 = {
let button = NewWidget::new(Button::with_text("Hello world"));
let mut harness = TestHarness::create_with_size(test_property_set(), button, (50, 50));
harness.edit_root_widget(|mut button| {
let mut label = Button::child_mut(&mut button);
let mut label = label.downcast();
Label::set_text(&mut label, "The quick brown fox jumps over the lazy dog");
label.insert_prop(ContentColor::new(ACCENT_COLOR));
Label::insert_style(&mut label, StyleProperty::FontSize(20.0));
});
harness.render()
};
assert!(image_1 == image_2);
}
#[test]
fn set_properties() {
let red = crate::palette::css::RED;
let button = NewWidget::new(Button::with_text("Some random text"));
let mut harness = TestHarness::create_with_size(test_property_set(), button, (200, 80));
harness.edit_root_widget(|mut button| {
button.insert_prop(BorderColor { color: red });
button.insert_prop(BorderWidth { width: 5.px() });
button.insert_prop(CornerRadius { radius: 20.px() });
button.insert_prop(Padding::from_vh(3.px(), 8.px()));
let mut label = Button::child_mut(&mut button);
label.insert_prop(ContentColor::new(red));
});
assert_render_snapshot!(harness, "button_set_properties");
}
#[test]
fn with_shadows() {
use crate::palette::css::ORANGE;
let grid = Grid::with_dimensions(2, 2)
.with(Button::with_text("A").prepare(), GridParams::pos(0, 0))
.with(Button::with_text("B").prepare(), GridParams::pos(1, 0))
.with(Button::with_text("C").prepare(), GridParams::pos(0, 1))
.with(Button::with_text("D").prepare(), GridParams::pos(1, 1));
let root_widget = NewWidget::new(grid).with_props(
PropertySet::new()
.with(Padding::all(20.px()))
.with(Gap::new(40.px())),
);
let test_params = TestHarnessParams::default().with_size((300, 300));
let mut harness = TestHarness::create_with(test_property_set(), root_widget, test_params);
harness.edit_root_widget(|mut grid| {
{
let mut button = Grid::get_mut(&mut grid, 0);
let mut button = button.downcast::<Button>();
button.insert_prop(BoxShadow::new(ORANGE, (10., 10.)));
}
{
let mut button = Grid::get_mut(&mut grid, 1);
let mut button = button.downcast::<Button>();
button.insert_prop(BoxShadow::new(ORANGE, (-10., 10.)).blur(5.px()));
}
{
let mut button = Grid::get_mut(&mut grid, 2);
let mut button = button.downcast::<Button>();
button.insert_prop(BoxShadow::new(ORANGE, (-10., -10.)).blur(0.px()));
}
{
let mut button = Grid::get_mut(&mut grid, 3);
let mut button = button.downcast::<Button>();
button.insert_prop(BoxShadow::new(ORANGE, (0., 0.)).blur(5.px()));
}
});
assert_render_snapshot!(harness, "button_shadows");
harness.edit_root_widget(|mut grid| {
{
let mut button = Grid::get_mut(&mut grid, 1);
let mut button = button.downcast::<Button>();
button.insert_prop(BoxShadow::new(ORANGE, (-10., 10.)).blur(2.5.px()));
}
});
assert_failing_render_snapshot!(harness, "button_shadows");
}
fn validate_noninteractive_child<W: Widget>(child: NewWidget<W>) {
let child_tag = WidgetTag::unique();
let child = child.with_tag(child_tag);
let mut button = Button::new(child).prepare();
button.properties.insert(Padding::all(10.px()));
let mut harness = TestHarness::create(test_property_set(), button);
let button_tag = harness.root_tag();
let button_id = harness.root_id();
harness.mouse_move_to_unchecked(child_tag);
let button = harness.get_widget(button_tag);
assert!(
button.ctx().is_hovered(),
"The child shouldn't prevent hover."
);
harness.mouse_button_press(None);
let button = harness.get_widget(button_tag);
assert!(
button.ctx().is_pointer_capture_target(),
"A non-interactive child shouldn't prevent pointer capture."
);
harness.mouse_button_release(None);
let (_, event_id) = harness
.pop_action::<<Button as Widget>::Action>()
.expect("There should be an action.");
assert_eq!(
event_id, button_id,
"The event should come from the button."
);
}
#[test]
fn label_child() {
let child = Label::new("Some text").prepare();
validate_noninteractive_child(child);
}
#[test]
fn sized_box_child() {
let child = SizedBox::empty().width(50.px()).height(50.px()).prepare();
validate_noninteractive_child(child);
}
#[test]
fn flex_child() {
let child = Flex::row()
.with_fixed(Label::new("Some text").prepare())
.prepare();
validate_noninteractive_child(child);
}
#[test]
fn textless_button() {
let button_tag = WidgetTag::unique();
let button = Button::with_text("").prepare().with_tag(button_tag);
let parent = Flex::row().with(button, 0.).prepare();
let params =
TestHarnessParams::size_and_padding((100, 40), TestHarnessParams::ROOT_PADDING);
let mut harness = TestHarness::create_with(test_property_set(), parent, params);
assert_render_snapshot!(harness, "button_no_text");
harness.mouse_click_on(button_tag, Some(PointerButton::Primary));
assert_matches!(
harness.pop_action::<ButtonPress>(),
Some((ButtonPress { .. }, ..))
);
}
}