use std::fmt::{self, Debug};
use std::rc::Rc;
use waft_embedder::TargetPlatform;
use waft_foundation::{App, Handle, Ref, ValueChanged};
use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
use waft_services::MouseCursorRef;
use crate::framework::{
BuildContext, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::widgets::basic::Semantics;
use crate::widgets::focus_manager::{AnyFocusNode, FocusNodeRef};
use crate::widgets::localizations::WidgetsLocalizations;
use crate::widgets::radio_group::{RadioClient, RadioClientData, RadioGroupRegistryRef};
use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
use crate::widgets::toggleable::{
AnyToggleableState, ToggleableStateMixin, ToggleableStateMixinData,
};
use crate::widgets::widget_state::WidgetStatePropertyRef;
pub type RadioBuilder = Rc<dyn Fn(&mut App, BuildContext, AnyToggleableState) -> WidgetRef>;
#[derive(Clone)]
pub struct RawRadio<T: Clone + PartialEq + 'static> {
pub key: Option<KeyRef>,
pub value: T,
pub mouse_cursor: WidgetStatePropertyRef<MouseCursorRef>,
pub toggleable: bool,
pub focus_node: FocusNodeRef,
pub autofocus: bool,
pub builder: RadioBuilder,
pub enabled: bool,
pub group_registry: Option<RadioGroupRegistryRef<T>>,
}
impl<T: Clone + PartialEq + 'static> RawRadio<T> {
#[allow(clippy::too_many_arguments)]
pub fn new(
value: T,
mouse_cursor: WidgetStatePropertyRef<MouseCursorRef>,
toggleable: bool,
focus_node: FocusNodeRef,
autofocus: bool,
group_registry: Option<RadioGroupRegistryRef<T>>,
enabled: bool,
builder: RadioBuilder,
) -> RawRadio<T> {
debug_assert!(
!enabled || group_registry.is_some(),
"an enabled raw radio must have a registry"
);
RawRadio {
key: None,
value,
mouse_cursor,
toggleable,
focus_node,
autofocus,
builder,
enabled,
group_registry,
}
}
pub fn key(mut self, key: KeyRef) -> RawRadio<T> {
self.key = Some(key);
self
}
}
impl<T: Clone + PartialEq + 'static> Debug for RawRadio<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RawRadio")
.field("enabled", &self.enabled)
.field("toggleable", &self.toggleable)
.field("autofocus", &self.autofocus)
.field("group_registry", &self.group_registry)
.finish_non_exhaustive()
}
}
impl<T: Clone + PartialEq + 'static> StatefulWidget for RawRadio<T> {
type State = RawRadioState<T>;
fn key(&self) -> Option<&KeyRef> {
self.key.as_ref()
}
fn create_state(&self) -> RawRadioState<T> {
RawRadioState {
state: StateData::new(),
ticker_provider: TickerProviderStateMixinData::new(),
toggleable: ToggleableStateMixinData::new(),
radio_client: RadioClientData::new(),
}
}
}
pub struct RawRadioState<T: Clone + PartialEq + 'static> {
state: StateData<RawRadio<T>>,
ticker_provider: TickerProviderStateMixinData,
toggleable: ToggleableStateMixinData,
radio_client: RadioClientData<T>,
}
impl<T: Clone + PartialEq + 'static> RawRadioState<T> {
fn handle_changed(self: Handle<Self>, app: &mut App, selected: Option<bool>) {
let registry = RadioClient::registry(self, app);
debug_assert!(registry.is_some());
let Some(registry) = registry else {
return;
};
if !selected.unwrap_or(true) {
return;
}
if selected.unwrap_or(false) {
let value = self.widget(app).value.clone();
registry.on_changed(app, Some(value));
} else {
registry.on_changed(app, None);
}
}
}
impl<T: Clone + PartialEq + 'static> TickerProviderStateMixin for RawRadioState<T> {
fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
&app.get(self).ticker_provider
}
fn ticker_provider_data_mut(
self: Handle<Self>,
app: &mut App,
) -> &mut TickerProviderStateMixinData {
&mut app.get_mut(self).ticker_provider
}
}
impl<T: Clone + PartialEq + 'static> TickerProviderObject for RawRadioState<T> {
fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
TickerProviderStateMixin::create_ticker(self, app, on_tick)
}
}
impl<T: Clone + PartialEq + 'static> RadioClient<T> for RawRadioState<T> {
crate::radio_client_accessors!(T);
fn tristate(self: Handle<Self>, app: &App) -> bool {
self.widget(app).toggleable
}
fn radio_value(self: Handle<Self>, app: &App) -> T {
self.widget(app).value.clone()
}
fn enabled(self: Handle<Self>, app: &App) -> bool {
ToggleableStateMixin::is_interactive(self, app)
}
fn focus_node(self: Handle<Self>, app: &App) -> AnyFocusNode {
self.widget(app).focus_node.handle()
}
}
impl<T: Clone + PartialEq + 'static> ToggleableStateMixin for RawRadioState<T> {
fn toggleable_data(self: Handle<Self>, app: &App) -> &ToggleableStateMixinData {
&app.get(self).toggleable
}
fn toggleable_data_mut(self: Handle<Self>, app: &mut App) -> &mut ToggleableStateMixinData {
&mut app.get_mut(self).toggleable
}
fn on_changed(self: Handle<Self>, app: &App) -> Option<ValueChanged<Option<bool>>> {
RadioClient::registry(self, app)?;
Some(Rc::new(move |app: &mut App, selected| {
self.handle_changed(app, selected)
}))
}
fn tristate(self: Handle<Self>, app: &App) -> bool {
self.widget(app).toggleable
}
fn value(self: Handle<Self>, app: &App) -> Option<bool> {
let registry = RadioClient::registry(self, app);
let group_value = registry.and_then(|registry| registry.group_value(app));
Some(group_value.as_ref() == Some(&self.widget(app).value))
}
fn is_interactive(self: Handle<Self>, app: &App) -> bool {
self.widget(app).enabled
}
}
impl<T: Clone + PartialEq + 'static> State for RawRadioState<T> {
type Widget = RawRadio<T>;
crate::state_accessors!();
fn init_state(self: Handle<Self>, app: &mut App) {
let registry = self.widget(app).group_registry.clone();
self.set_registry(app, registry);
ToggleableStateMixin::init_state(self, app);
}
fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &RawRadio<T>) {
let registry = self.widget(app).group_registry.clone();
self.set_registry(app, registry);
self.animate_to_value(app); }
fn activate(self: Handle<Self>, app: &mut App) {
TickerProviderStateMixin::activate(self, app);
}
fn dispose(self: Handle<Self>, app: &mut App) {
ToggleableStateMixin::dispose(self, app);
TickerProviderStateMixin::dispose(self, app);
self.set_registry(app, None);
}
fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
let accessibility_selected: Option<bool>;
let mut semantics_hint: Option<String> = None;
match app.platform().target_platform() {
TargetPlatform::Android
| TargetPlatform::Fuchsia
| TargetPlatform::Linux
| TargetPlatform::Windows => {
accessibility_selected = None;
semantics_hint = None;
}
TargetPlatform::IOS | TargetPlatform::MacOS => {
accessibility_selected = self.value(app);
if !self.value(app).unwrap_or(false) {
let localizations = <dyn WidgetsLocalizations>::of(app, context);
semantics_hint = Some(localizations.radio_button_unselected_label());
}
}
}
let widget = self.widget(app);
let focus_node = widget.focus_node.clone();
let autofocus = widget.autofocus;
let mouse_cursor = Rc::clone(&widget.mouse_cursor);
let builder = Rc::clone(&widget.builder);
let child = builder(app, context, self.as_toggleable_state());
let mut semantics = Semantics::new().in_mutually_exclusive_group(true);
if let Some(checked) = self.value(app) {
semantics = semantics.checked(checked);
}
if let Some(selected) = accessibility_selected {
semantics = semantics.selected(selected);
}
if let Some(hint) = semantics_hint {
semantics = semantics.hint(hint);
}
semantics
.child(self.build_toggleable_with_child(
app,
Some(focus_node),
None,
autofocus,
Some(mouse_cursor),
child,
))
.into_widget()
}
}
#[cfg(test)]
mod tests {
use std::any::Any;
use std::cell::{Cell, RefCell};
use std::time::Duration;
use waft_foundation::Ref;
use waft_embedder::{Canvas, Size};
use waft_rendering::CustomPainter;
use waft_services::SystemMouseCursors;
use super::*;
use crate::framework::IntoWidget;
use crate::testing::{WidgetTester, find, test_widgets};
use crate::widgets::basic::{Builder, Center, CustomPaint, Directionality, SizedBox};
use crate::widgets::focus_manager::FocusNode;
use crate::widgets::radio_group::{AnyRadioClient, RadioGroup, RadioGroupRegistry};
use crate::widgets::widget_state::WidgetStateProperty;
use waft_embedder::TextDirection;
struct TestRegistry {
group_value: Option<u32>,
clients: Vec<AnyRadioClient<u32>>,
}
impl RadioGroupRegistry<u32> for TestRegistry {
fn group_value(self: Handle<Self>, app: &App) -> Option<u32> {
app.get(self).group_value
}
fn register_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<u32>) {
app.get_mut(self).clients.push(radio);
}
fn unregister_client(self: Handle<Self>, app: &mut App, radio: AnyRadioClient<u32>) {
app.get_mut(self).clients.retain(|client| *client != radio);
}
fn on_changed(self: Handle<Self>, app: &mut App, value: Option<u32>) {
app.get_mut(self).group_value = value;
}
}
fn registry(app: &mut App) -> Ref<TestRegistry> {
app.create(TestRegistry {
group_value: None,
clients: Vec::new(),
})
}
fn raw_radio(
node: FocusNodeRef,
registry: Option<RadioGroupRegistryRef<u32>>,
enabled: bool,
toggleable: bool,
captured: Rc<Cell<Option<AnyToggleableState>>>,
child: impl Fn() -> WidgetRef + 'static,
) -> RawRadio<u32> {
RawRadio::new(
0,
<dyn WidgetStateProperty<MouseCursorRef>>::all(SystemMouseCursors::CLICK.into()),
toggleable,
node,
false,
registry,
enabled,
Rc::new(move |_app, _context, state| {
captured.set(Some(state));
child()
}),
)
}
struct TestPainter;
impl CustomPainter for TestPainter {
fn paint(&self, _app: &mut App, _canvas: &mut Canvas, _size: Size) {}
fn should_repaint(&self, _app: &App, _old_delegate: &dyn CustomPainter) -> bool {
true
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn painted_box() -> WidgetRef {
CustomPaint::new()
.size(Size::new(40.0, 40.0))
.painter(TestPainter)
.into_widget()
}
fn focus_node(tester: &WidgetTester) -> FocusNodeRef {
tester.update(|app| FocusNode::new(app).erase())
}
#[test]
fn a_tap_selects_the_radio_in_its_registry() {
test_widgets(|tester| {
let node = focus_node(tester);
let registry = tester.update(registry);
let captured = Rc::new(Cell::new(None));
let build = |captured: &Rc<Cell<Option<AnyToggleableState>>>| {
raw_radio(
node.clone(),
Some(registry.erase()),
true,
true,
Rc::clone(captured),
painted_box,
)
};
tester.pump_widget(build(&captured));
let actual_state = captured.get().expect("the builder ran");
{
let app = tester.cell.borrow();
assert!(actual_state.tristate(&app));
assert_eq!(actual_state.value(&app), Some(false));
assert_eq!(app.get(®istry).group_value, None);
let state = app
.handle::<RawRadioState<u32>>(actual_state.id())
.expect("the radio's state");
assert!(
app.get(®istry)
.clients
.contains(&state.as_radio_client())
);
}
tester.tap(find::by_type::<RawRadio<u32>>());
tester.pump_widget(build(&captured));
let app = tester.cell.borrow();
assert_eq!(app.get(®istry).group_value, Some(0));
assert_eq!(actual_state.value(&app), Some(true));
});
}
#[test]
fn a_disabled_radio_does_not_report_a_tap() {
test_widgets(|tester| {
let node = focus_node(tester);
let registry = tester.update(registry);
let captured = Rc::new(Cell::new(None));
tester.pump_widget(raw_radio(
node,
Some(registry.erase()),
false,
true,
captured,
painted_box,
));
tester.tap(find::by_type::<RawRadio<u32>>());
assert_eq!(tester.cell.borrow().get(®istry).group_value, None);
});
}
#[test]
#[should_panic(expected = "an enabled raw radio must have a registry")]
fn an_enabled_radio_without_a_registry_is_rejected() {
test_widgets(|tester| {
let node = focus_node(tester);
raw_radio(
node,
None,
true,
true,
Rc::new(Cell::new(None)),
painted_box,
);
});
}
fn string_radio_group(
node: FocusNodeRef,
group_value: Option<String>,
changes: Rc<RefCell<Vec<Option<String>>>>,
captured: Rc<Cell<Option<AnyToggleableState>>>,
) -> WidgetRef {
let mut group = RadioGroup::<String>::new(
Rc::new(move |_app, value| changes.borrow_mut().push(value)),
Builder::new(move |app, context| {
let captured = Rc::clone(&captured);
RawRadio::new(
String::from("lafayette"),
<dyn WidgetStateProperty<MouseCursorRef>>::all(
SystemMouseCursors::CLICK.into(),
),
true,
node.clone(),
false,
RadioGroup::<String>::maybe_of(app, context),
true,
Rc::new(move |_app, _context, state| {
captured.set(Some(state));
painted_box()
}),
)
.into_widget()
}),
);
if let Some(group_value) = group_value {
group = group.group_value(group_value);
}
group.into_widget()
}
#[test]
fn a_radio_takes_a_string_value_compared_with_eq() {
test_widgets(|tester| {
let node = focus_node(tester);
let changes: Rc<RefCell<Vec<Option<String>>>> = Rc::default();
let captured = Rc::new(Cell::new(None));
tester.pump_widget(string_radio_group(
node.clone(),
None,
Rc::clone(&changes),
Rc::clone(&captured),
));
let state = captured.get().expect("the builder ran");
assert_eq!(state.value(&tester.cell.borrow()), Some(false));
tester.tap(find::by_type::<RawRadio<String>>());
assert_eq!(*changes.borrow(), [Some(String::from("lafayette"))]);
tester.pump_widget(string_radio_group(
node,
Some(String::from("lafayette")),
Rc::clone(&changes),
Rc::clone(&captured),
));
assert_eq!(state.value(&tester.cell.borrow()), Some(true));
tester.tap(find::by_type::<RawRadio<String>>());
assert_eq!(*changes.borrow(), [Some(String::from("lafayette")), None]);
});
}
#[test]
#[should_panic(expected = "No WidgetsLocalizations found")]
fn an_unselected_radio_on_ios_reads_the_widgets_localizations() {
let mut tester = WidgetTester::on(TargetPlatform::IOS);
let node = focus_node(&tester);
let registry = tester.update(registry);
tester.pump_widget(raw_radio(
node,
Some(registry.erase()),
true,
false,
Rc::new(Cell::new(None)),
painted_box,
));
}
#[test]
fn a_radio_at_zero_area_does_not_crash() {
test_widgets(|tester| {
let node = focus_node(tester);
let registry = tester.update(registry);
let captured = Rc::new(Cell::new(None));
let radio = raw_radio(
node,
Some(registry.erase()),
true,
false,
captured.clone(),
|| SizedBox::square(Some(24.0)).into_widget(),
);
tester.pump_widget(Directionality::new(
TextDirection::Ltr,
Center::new().child(SizedBox::shrink().child(radio)),
));
tester.pump_by(Duration::from_millis(16));
let app = tester.cell.borrow();
let state = captured.get().expect("the builder ran");
let size = state.context(&app).size(&app);
assert_eq!(size, Some(Size::ZERO));
});
}
}