Skip to main content

waft_winui/controls/
radio_button.rs

1//! XAML `RadioButton` with the `DefaultRadioButtonStyle` of `RadioButton_themeresources.xaml`.
2//!
3//! Template: `RootGrid` (the control's `Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`) with columns 20 and `*`; in column 0 a 32-high grid aligned `Top` holding `OuterEllipse` (the unchecked ring), `CheckOuterEllipse` (the checked ring, shown in the `Checked` state), `CheckGlyph` (the dot, shown when checked; its `Width` / `Height` animate per common state) and `PressedCheckGlyph` (a 4 pt dot that grows to 10 while pressed); in column 1 the `ContentPresenter` with `Margin="{TemplateBinding Padding}"` (8,6,0,0), aligned `Left` / `Top`.
4//!
5//! Behaviour (`RadioButton_Partial.cpp`, `ToggleButton_Partial.cpp`): `ToggleButton::OnClick` calls `OnToggle`, which `RadioButton::OnToggle` overrides to set `IsChecked` to `true` only, so a checked radio button does not uncheck on click; `RadioButton::UpdateRadioButtonGroup` unchecks the other members of the group when one becomes checked.
6
7use crate::{
8    Brush, ColumnDefinition, CommonState, CommonStates, ControlStates, FocusVisual, Grid, GridCell,
9    GridLength, ThemeResources, control_text_style, fast_out_slow_in,
10};
11use std::{fmt, time::Duration};
12use waft_embedder::{Canvas, Color, FontWeight, Offset, Size};
13use waft_foundation::{App, Listener};
14use waft_painting::{AlignmentGeometry, EdgeInsetsGeometry};
15use waft_rendering::{BoxConstraints, CustomPainter};
16use waft_widgets::*;
17
18/// `OuterEllipse` and `CheckOuterEllipse`: `Width="20" Height="20"`.
19pub const RING_SIZE: f64 = 20.0;
20/// The grid the ellipses centre in: `Height="32"`.
21pub const GLYPH_AREA_HEIGHT: f64 = 32.0;
22/// The first column of `RootGrid`: `Width="20"`.
23pub const GLYPH_COLUMN_WIDTH: f64 = 20.0;
24/// `PressedCheckGlyph`: `Width="4" Height="4"` until the `Pressed` storyboard grows it.
25pub const PRESSED_GLYPH_SIZE: f64 = 4.0;
26/// The size the `Pressed` storyboard animates `PressedCheckGlyph` to.
27pub const PRESSED_GLYPH_PRESSED_SIZE: f64 = 10.0;
28/// The size the `Disabled` storyboard animates `CheckGlyph` to.
29pub const CHECK_GLYPH_DISABLED_SIZE: f64 = 14.0;
30/// The default `StrokeThickness` of a XAML `Shape`, which `CheckGlyph` keeps.
31pub const CHECK_GLYPH_STROKE_THICKNESS: f64 = 1.0;
32/// The style's `Padding`, the `ContentPresenter`'s margin: left, top, right, bottom.
33pub const RADIO_BUTTON_PADDING: [f64; 4] = [8.0, 6.0, 0.0, 0.0];
34/// The style's `MinWidth`.
35pub const RADIO_BUTTON_MIN_WIDTH: f64 = 120.0;
36/// The style's `FocusVisualMargin`.
37pub const RADIO_BUTTON_FOCUS_VISUAL_MARGIN: [f64; 4] = [-7.0, -3.0, -7.0, -3.0];
38
39/// The size `CheckGlyph` has in each common state: `RadioButtonCheckGlyphSize` (12) at rest, the `PointerOver` storyboard's 14, the `Pressed` storyboard's 10 and the `Disabled` storyboard's 14.
40pub fn check_glyph_size(r: &ThemeResources, state: CommonState) -> f64 {
41    match state {
42        CommonState::Normal => r.radio_button_check_glyph_size,
43        CommonState::PointerOver => r.radio_button_check_glyph_pointer_over_size,
44        CommonState::Pressed => r.radio_button_check_glyph_pressed_over_size,
45        CommonState::Disabled => CHECK_GLYPH_DISABLED_SIZE,
46    }
47}
48
49/// How long `CheckGlyph` takes to reach its size for `state`: the `KeyTime` of the state's `SplineDoubleKeyFrame` (`ControlNormalAnimationDuration` for `PointerOver` and `Pressed`, `ControlFastAnimationDuration` for `Disabled`). `Normal` declares no size animation, so the glyph returns to its base size at once, as a stopped storyboard releases the property.
50pub fn check_glyph_duration(r: &ThemeResources, state: CommonState) -> Duration {
51    match state {
52        CommonState::Normal => Duration::ZERO,
53        CommonState::PointerOver | CommonState::Pressed => r.control_normal_animation_duration,
54        CommonState::Disabled => r.control_fast_animation_duration,
55    }
56}
57
58/// XAML `RadioButton`: `IsChecked` with `Checked`, `Content`, `IsEnabled`. The group is the caller's: the `checked` handler fires when an unchecked button is activated, and the caller checks it and unchecks the others.
59#[derive(Clone)]
60pub struct RadioButton {
61    pub is_checked: bool,
62    /// XAML `Checked`: raised when activation checks the button.
63    pub checked: Listener,
64    pub content: Option<WidgetRef>,
65    pub is_enabled: bool,
66    pub key: Option<KeyRef>,
67}
68
69impl RadioButton {
70    pub fn new(is_checked: bool, checked: impl Fn(&mut App) + 'static) -> RadioButton {
71        RadioButton {
72            is_checked,
73            checked: Listener::new(checked),
74            content: None,
75            is_enabled: true,
76            key: None,
77        }
78    }
79
80    /// XAML `Content`.
81    #[cfg_attr(debug_assertions, track_caller)]
82    pub fn content<K>(mut self, content: impl IntoWidget<K>) -> RadioButton {
83        self.content = Some(content.into_widget());
84        self
85    }
86
87    /// XAML `IsEnabled`.
88    pub fn is_enabled(mut self, enabled: bool) -> RadioButton {
89        self.is_enabled = enabled;
90        self
91    }
92
93    pub fn key(mut self, key: KeyRef) -> RadioButton {
94        self.key = Some(key);
95        self
96    }
97}
98
99impl fmt::Debug for RadioButton {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        f.debug_struct("RadioButton")
102            .field("is_checked", &self.is_checked)
103            .field("is_enabled", &self.is_enabled)
104            .finish_non_exhaustive()
105    }
106}
107
108impl StatelessWidget for RadioButton {
109    fn key(&self) -> Option<&KeyRef> {
110        self.key.as_ref()
111    }
112
113    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
114        let widget = self.clone();
115        // `RadioButton::OnToggle`: `put_IsChecked(TRUE)`; a value that does not change raises nothing.
116        let checked = self.checked.clone();
117        let is_checked = self.is_checked;
118        let click = Listener::new(move |app| {
119            if !is_checked {
120                checked.call(app);
121            }
122        });
123        // `RadioButton::Initialize`: `SetAcceptsReturn(false)`.
124        CommonStates::new(click, move |app, context, states| {
125            template(app, context, &widget, states)
126        })
127        .is_enabled(self.is_enabled)
128        .accepts_return(false)
129        .into_widget()
130    }
131}
132
133/// The `{ThemeResource …}` values the `CommonStates` storyboards name for one state.
134struct RadioBrushes {
135    foreground: Color,
136    background: Color,
137    border: Color,
138    outer_ellipse_stroke: Color,
139    outer_ellipse_fill: Color,
140    check_outer_ellipse_stroke: Color,
141    check_outer_ellipse_fill: Color,
142    check_glyph_fill: Color,
143    /// `RadioButtonCheckGlyphStroke*`: `CircleElevationBorderBrush`.
144    check_glyph_stroke: [(f64, Color); 2],
145}
146
147fn brushes(r: &ThemeResources, state: CommonState) -> RadioBrushes {
148    match state {
149        CommonState::Normal => RadioBrushes {
150            foreground: r.radio_button_foreground,
151            background: r.radio_button_background,
152            border: r.radio_button_border_brush,
153            outer_ellipse_stroke: r.radio_button_outer_ellipse_stroke,
154            outer_ellipse_fill: r.radio_button_outer_ellipse_fill,
155            check_outer_ellipse_stroke: r.radio_button_outer_ellipse_checked_stroke,
156            check_outer_ellipse_fill: r.radio_button_outer_ellipse_checked_fill,
157            check_glyph_fill: r.radio_button_check_glyph_fill,
158            check_glyph_stroke: r.radio_button_check_glyph_stroke,
159        },
160        CommonState::PointerOver => RadioBrushes {
161            foreground: r.radio_button_foreground_pointer_over,
162            background: r.radio_button_background_pointer_over,
163            border: r.radio_button_border_brush_pointer_over,
164            outer_ellipse_stroke: r.radio_button_outer_ellipse_stroke_pointer_over,
165            outer_ellipse_fill: r.radio_button_outer_ellipse_fill_pointer_over,
166            check_outer_ellipse_stroke: r.radio_button_outer_ellipse_checked_stroke_pointer_over,
167            check_outer_ellipse_fill: r.radio_button_outer_ellipse_checked_fill_pointer_over,
168            check_glyph_fill: r.radio_button_check_glyph_fill_pointer_over,
169            check_glyph_stroke: r.radio_button_check_glyph_stroke_pointer_over,
170        },
171        CommonState::Pressed => RadioBrushes {
172            foreground: r.radio_button_foreground_pressed,
173            background: r.radio_button_background_pressed,
174            border: r.radio_button_border_brush_pressed,
175            outer_ellipse_stroke: r.radio_button_outer_ellipse_stroke_pressed,
176            outer_ellipse_fill: r.radio_button_outer_ellipse_fill_pressed,
177            check_outer_ellipse_stroke: r.radio_button_outer_ellipse_checked_stroke_pressed,
178            check_outer_ellipse_fill: r.radio_button_outer_ellipse_checked_fill_pressed,
179            check_glyph_fill: r.radio_button_check_glyph_fill_pressed,
180            check_glyph_stroke: r.radio_button_check_glyph_stroke_pressed,
181        },
182        CommonState::Disabled => RadioBrushes {
183            foreground: r.radio_button_foreground_disabled,
184            background: r.radio_button_background_disabled,
185            border: r.radio_button_border_brush_disabled,
186            outer_ellipse_stroke: r.radio_button_outer_ellipse_stroke_disabled,
187            outer_ellipse_fill: r.radio_button_outer_ellipse_fill_disabled,
188            check_outer_ellipse_stroke: r.radio_button_outer_ellipse_checked_stroke_disabled,
189            check_outer_ellipse_fill: r.radio_button_outer_ellipse_checked_fill_disabled,
190            check_glyph_fill: r.radio_button_check_glyph_fill_disabled,
191            check_glyph_stroke: r.radio_button_check_glyph_stroke_disabled,
192        },
193    }
194}
195
196/// The `ControlTemplate` of `DefaultRadioButtonStyle` for one set of states.
197fn template(
198    app: &mut App,
199    context: BuildContext,
200    widget: &RadioButton,
201    states: ControlStates,
202) -> WidgetRef {
203    let resources = ThemeResources::of(app, context);
204    let r = &resources;
205    let brushes = brushes(r, states.common);
206    let glyphs = glyph_area(r, &brushes, widget.is_checked, states.common);
207    // `ContentPresenter`: `Margin="{TemplateBinding Padding}"`, `HorizontalContentAlignment="Left"`, `VerticalContentAlignment="Top"`, `TextWrapping="Wrap"`.
208    let text = control_text_style(
209        &resources,
210        r.control_content_theme_font_size,
211        FontWeight::W400,
212        brushes.foreground,
213    );
214    let [left, top, right, bottom] = RADIO_BUTTON_PADDING;
215    let mut presenter = Align::new()
216        .alignment(AlignmentGeometry::TOP_LEFT)
217        .width_factor(1.0)
218        .height_factor(1.0);
219    if let Some(content) = &widget.content {
220        presenter = presenter.child(
221            Padding::new(EdgeInsetsGeometry::from_ltrb(left, top, right, bottom))
222                .child(DefaultTextStyle::new(text, content.clone())),
223        );
224    }
225    // `RootGrid`: the control's `BorderThickness` is the `Control` default, 0.
226    let root = Grid::new()
227        .background(Brush::Solid(brushes.background))
228        .border_brush(Brush::Solid(brushes.border))
229        .border_thickness(0.0)
230        .corner_radius(r.control_corner_radius[0])
231        .column_definitions([
232            ColumnDefinition::new(GridLength::pixel(GLYPH_COLUMN_WIDTH)),
233            ColumnDefinition::new(GridLength::STAR),
234        ])
235        .children([
236            GridCell::new(glyphs).into_widget(),
237            GridCell::new(presenter).column(1).into_widget(),
238        ]);
239    let body =
240        ConstrainedBox::new(BoxConstraints::new().min_width(RADIO_BUTTON_MIN_WIDTH)).child(root);
241    FocusVisual::new(body, resources.theme)
242        .visible(states.focused)
243        .margin(RADIO_BUTTON_FOCUS_VISUAL_MARGIN)
244        .corner_radius(r.control_corner_radius[0])
245        .into_widget()
246}
247
248/// The 32-high grid aligned `Top` in column 0, with the two rings and the two dots centred in it.
249fn glyph_area(
250    r: &ThemeResources,
251    brushes: &RadioBrushes,
252    is_checked: bool,
253    state: CommonState,
254) -> WidgetRef {
255    // `OuterEllipse`: `Opacity` 0 in the `Checked` state; `CheckOuterEllipse`: `Opacity="0"`, 1 in `Checked`.
256    let ring = if is_checked {
257        Ellipse::new(
258            Brush::Solid(brushes.check_outer_ellipse_fill),
259            Brush::Solid(brushes.check_outer_ellipse_stroke),
260        )
261    } else {
262        Ellipse::new(
263            Brush::Solid(brushes.outer_ellipse_fill),
264            Brush::Solid(brushes.outer_ellipse_stroke),
265        )
266    };
267    let ring = SizedBox::new()
268        .width(RING_SIZE)
269        .height(RING_SIZE)
270        .child(ring.stroke_thickness(r.radio_button_border_theme_thickness))
271        .into_widget();
272    let mut layers = vec![Center::new().child(ring).into_widget()];
273    // `CheckGlyph`: `Opacity="0"`, 1 in `Checked`. Its `Stroke` is the `CommonStates` storyboards' `RadioButtonCheckGlyphStroke*` (`CircleElevationBorderBrush`) until the `Checked` storyboard, applied after them, sets `RadioButtonCheckGlyphStrokeChecked` (`AccentControlElevationBorderBrush`).
274    let stroke = if is_checked {
275        Brush::ControlElevation(r.radio_button_check_glyph_stroke_checked)
276    } else {
277        Brush::CircleElevation(brushes.check_glyph_stroke)
278    };
279    let glyph = Ellipse::new(Brush::Solid(brushes.check_glyph_fill), stroke)
280        .stroke_thickness(CHECK_GLYPH_STROKE_THICKNESS);
281    let size = check_glyph_size(r, state);
282    let glyph = AnimatedContainer::new(check_glyph_duration(r, state))
283        .curve(fast_out_slow_in(r))
284        .width(size)
285        .height(size)
286        .child(glyph);
287    layers.push(
288        Center::new()
289            .child(Opacity::new(if is_checked { 1.0 } else { 0.0 }).child(glyph))
290            .into_widget(),
291    );
292    // `PressedCheckGlyph`: `Opacity="0"`, 1 in `Pressed`, where it grows from 4 to 10 over `ControlFastAnimationDuration`; a `Border` with `CornerRadius="6"` and no `BorderThickness`, so a filled circle.
293    let pressed = state == CommonState::Pressed;
294    let pressed_glyph = Ellipse::new(
295        Brush::Solid(brushes.check_glyph_fill),
296        Brush::Solid(Color::from_argb(0, 0, 0, 0)),
297    )
298    .stroke_thickness(0.0);
299    let size = if pressed {
300        PRESSED_GLYPH_PRESSED_SIZE
301    } else {
302        PRESSED_GLYPH_SIZE
303    };
304    let duration = if pressed {
305        r.control_fast_animation_duration
306    } else {
307        Duration::ZERO
308    };
309    let pressed_glyph = AnimatedContainer::new(duration)
310        .curve(fast_out_slow_in(r))
311        .width(size)
312        .height(size)
313        .child(pressed_glyph);
314    layers.push(
315        Center::new()
316            .child(Opacity::new(if pressed { 1.0 } else { 0.0 }).child(pressed_glyph))
317            .into_widget(),
318    );
319    let area = SizedBox::new()
320        .height(GLYPH_AREA_HEIGHT)
321        .child(Stack::new().children(layers))
322        .into_widget();
323    Align::new()
324        .alignment(AlignmentGeometry::TOP_CENTER)
325        .width_factor(1.0)
326        .height_factor(1.0)
327        .child(area)
328        .into_widget()
329}
330
331/// XAML `Ellipse`: `Fill` and `Stroke` at `StrokeThickness`, the stroke centred on the geometry inset by half the thickness so it stays inside the bounds, as a `Shape` lays out.
332#[derive(Clone, Debug, PartialEq)]
333pub struct Ellipse {
334    pub fill: Brush,
335    pub stroke: Brush,
336    pub stroke_thickness: f64,
337}
338
339impl Ellipse {
340    pub fn new(fill: Brush, stroke: Brush) -> Ellipse {
341        Ellipse {
342            fill,
343            stroke,
344            stroke_thickness: 1.0,
345        }
346    }
347
348    /// XAML `StrokeThickness`.
349    pub fn stroke_thickness(mut self, thickness: f64) -> Ellipse {
350        self.stroke_thickness = thickness;
351        self
352    }
353}
354
355impl StatelessWidget for Ellipse {
356    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
357        CustomPaint::new().painter(self.clone()).into_widget()
358    }
359}
360
361impl CustomPainter for Ellipse {
362    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
363        let bounds = Offset::ZERO & size;
364        let geometry = bounds.deflate(self.stroke_thickness / 2.0);
365        if matches!(self.fill, Brush::Acrylic(_)) || self.fill.representative_color().a > 0.0 {
366            self.fill.paint_oval(canvas, geometry, bounds);
367        }
368        if self.stroke_thickness > 0.0
369            && (matches!(self.stroke, Brush::Acrylic(_))
370                || self.stroke.representative_color().a > 0.0)
371        {
372            self.stroke
373                .paint_oval_stroke(canvas, geometry, bounds, self.stroke_thickness);
374        }
375    }
376
377    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
378        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
379    }
380
381    fn as_any(&self) -> &dyn std::any::Any {
382        self
383    }
384}