Skip to main content

waft_winui/controls/
toggle_button.rs

1//! XAML `ToggleButton` with the `DefaultToggleButtonStyle` of `ToggleButton_themeresources.xaml`.
2//!
3//! The template is one `ContentPresenter` (`x:Name="ContentPresenter"`) carrying `Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`, `Padding`, `Foreground` and `BackgroundSizing`, with a `BrushTransition` of 83 ms on `Background`. `CommonStates` has twelve states: `Normal`, `PointerOver`, `Pressed` and `Disabled`, their `Checked*` twins (which also set `BackgroundSizing` to `ToggleButtonCheckedStateBackgroundSizing`) and their `Indeterminate*` twins; `ToggleButton::ChangeVisualState` (`ToggleButton_Partial.cpp`) picks the row from `IsChecked` and the column from the pointer.
4
5use crate::{
6    BackgroundSizing, Brush, ColorTransition, CommonState, CommonStates, ControlBorder,
7    ControlStates, FocusVisual, ThemeResources, control_text_style,
8};
9use std::{fmt, rc::Rc};
10use waft_embedder::{Color, FontWeight};
11use waft_foundation::{App, Listener};
12use waft_painting::AlignmentGeometry;
13use waft_widgets::*;
14
15/// The `FocusVisualMargin` the style sets.
16pub const TOGGLE_BUTTON_FOCUS_VISUAL_MARGIN: [f64; 4] = [-3.0; 4];
17
18/// The brushes the style resolves to in one of its twelve states.
19#[derive(Clone, Copy, Debug, PartialEq)]
20pub struct ToggleButtonBrushes {
21    pub background: Color,
22    pub border: Brush,
23    pub foreground: Color,
24    pub background_sizing: BackgroundSizing,
25}
26
27/// The `{ThemeResource …}` values the `CommonStates` storyboards name for `is_checked` (`Some(true)` the `Checked*` row, `None` the `Indeterminate*` row) and `state`.
28pub fn toggle_button_brushes(
29    resources: &ThemeResources,
30    is_checked: Option<bool>,
31    state: CommonState,
32) -> ToggleButtonBrushes {
33    let r = resources;
34    let unchecked = |background, border, foreground| ToggleButtonBrushes {
35        background,
36        border,
37        foreground,
38        background_sizing: BackgroundSizing::InnerBorderEdge,
39    };
40    let checked = |background, border, foreground| ToggleButtonBrushes {
41        background,
42        border,
43        foreground,
44        background_sizing: resources.toggle_button_checked_state_background_sizing,
45    };
46    match (is_checked, state) {
47        // `Normal`: the style's own setters.
48        (Some(false), CommonState::Normal) => unchecked(
49            r.toggle_button_background,
50            Brush::ControlElevation(r.toggle_button_border_brush),
51            r.toggle_button_foreground,
52        ),
53        (Some(false), CommonState::PointerOver) => unchecked(
54            r.toggle_button_background_pointer_over,
55            Brush::ControlElevation(r.toggle_button_border_brush_pointer_over),
56            r.toggle_button_foreground_pointer_over,
57        ),
58        (Some(false), CommonState::Pressed) => unchecked(
59            r.toggle_button_background_pressed,
60            Brush::Solid(r.toggle_button_border_brush_pressed),
61            r.toggle_button_foreground_pressed,
62        ),
63        (Some(false), CommonState::Disabled) => unchecked(
64            r.toggle_button_background_disabled,
65            Brush::Solid(r.toggle_button_border_brush_disabled),
66            r.toggle_button_foreground_disabled,
67        ),
68        (Some(true), CommonState::Normal) => checked(
69            r.toggle_button_background_checked,
70            Brush::ControlElevation(r.toggle_button_border_brush_checked),
71            r.toggle_button_foreground_checked,
72        ),
73        (Some(true), CommonState::PointerOver) => checked(
74            r.toggle_button_background_checked_pointer_over,
75            Brush::ControlElevation(r.toggle_button_border_brush_checked_pointer_over),
76            r.toggle_button_foreground_checked_pointer_over,
77        ),
78        (Some(true), CommonState::Pressed) => checked(
79            r.toggle_button_background_checked_pressed,
80            Brush::Solid(r.toggle_button_border_brush_checked_pressed),
81            r.toggle_button_foreground_checked_pressed,
82        ),
83        // `CheckedDisabled` names no `BackgroundSizing`, so the style's `InnerBorderEdge` holds.
84        (Some(true), CommonState::Disabled) => unchecked(
85            r.toggle_button_background_checked_disabled,
86            Brush::Solid(r.toggle_button_border_brush_checked_disabled),
87            r.toggle_button_foreground_checked_disabled,
88        ),
89        (None, CommonState::Normal) => unchecked(
90            r.toggle_button_background_indeterminate,
91            Brush::ControlElevation(r.toggle_button_border_brush_indeterminate),
92            r.toggle_button_foreground_indeterminate,
93        ),
94        (None, CommonState::PointerOver) => unchecked(
95            r.toggle_button_background_indeterminate_pointer_over,
96            Brush::ControlElevation(r.toggle_button_border_brush_indeterminate_pointer_over),
97            r.toggle_button_foreground_indeterminate_pointer_over,
98        ),
99        (None, CommonState::Pressed) => unchecked(
100            r.toggle_button_background_indeterminate_pressed,
101            Brush::Solid(r.toggle_button_border_brush_indeterminate_pressed),
102            r.toggle_button_foreground_indeterminate_pressed,
103        ),
104        (None, CommonState::Disabled) => unchecked(
105            r.toggle_button_background_indeterminate_disabled,
106            Brush::Solid(r.toggle_button_border_brush_indeterminate_disabled),
107            r.toggle_button_foreground_indeterminate_disabled,
108        ),
109    }
110}
111
112/// The value `IsChecked` takes after a toggle; `ToggleButton::OnToggleImpl`: indeterminate becomes unchecked, unchecked becomes checked, and checked becomes indeterminate when `IsThreeState` and unchecked otherwise.
113pub fn next_is_checked(is_checked: Option<bool>, is_three_state: bool) -> Option<bool> {
114    match is_checked {
115        None => Some(false),
116        Some(true) if is_three_state => None,
117        Some(true) => Some(false),
118        Some(false) => Some(true),
119    }
120}
121
122/// The `Checked`, `Unchecked` and `Indeterminate` events as one handler, given the value the button wants.
123pub type ToggleButtonCheckedHandler = Rc<dyn Fn(&mut App, Option<bool>)>;
124
125/// Builds a source ToggleButton template while retaining native toggle and keyboard behavior.
126pub type ToggleButtonTemplate =
127    Rc<dyn Fn(&mut App, BuildContext, Option<bool>, Option<WidgetRef>, ControlStates) -> WidgetRef>;
128
129/// XAML `ToggleButton`: `IsChecked` (`Some(true)`, `Some(false)` or `None` for indeterminate) with `IsThreeState`, `Content`, and `Click` after each toggle.
130#[derive(Clone)]
131pub struct ToggleButton {
132    pub is_checked: Option<bool>,
133    /// XAML `Checked` / `Unchecked` / `Indeterminate`, with the value the button wants.
134    pub checked: ToggleButtonCheckedHandler,
135    pub content: Option<WidgetRef>,
136    /// XAML `IsThreeState`: whether a toggle from checked goes through indeterminate.
137    pub is_three_state: bool,
138    /// XAML `Click`, raised after the toggle as `ToggleButton::OnClick` does.
139    pub click: Option<Listener>,
140    pub is_enabled: bool,
141
142    /// Optional source template used by compound controls such as Expander.
143    pub template: Option<ToggleButtonTemplate>,
144
145    pub key: Option<KeyRef>,
146}
147
148impl ToggleButton {
149    pub fn new(
150        is_checked: Option<bool>,
151        checked: impl Fn(&mut App, Option<bool>) + 'static,
152    ) -> ToggleButton {
153        ToggleButton {
154            is_checked,
155            checked: Rc::new(checked),
156            content: None,
157            is_three_state: false,
158            click: None,
159            is_enabled: true,
160            template: None,
161            key: None,
162        }
163    }
164
165    /// A text `Content`, as `<ToggleButton Content="…"/>`.
166    pub fn text(
167        text: impl Into<String>,
168        is_checked: Option<bool>,
169        checked: impl Fn(&mut App, Option<bool>) + 'static,
170    ) -> ToggleButton {
171        ToggleButton::new(is_checked, checked).content(Text::new(text))
172    }
173
174    /// XAML `Content`.
175    #[cfg_attr(debug_assertions, track_caller)]
176    pub fn content<K>(mut self, content: impl IntoWidget<K>) -> ToggleButton {
177        self.content = Some(content.into_widget());
178        self
179    }
180
181    /// XAML `IsThreeState`.
182    pub fn is_three_state(mut self, is_three_state: bool) -> ToggleButton {
183        self.is_three_state = is_three_state;
184        self
185    }
186
187    /// XAML `Click`.
188    pub fn click(mut self, click: Listener) -> ToggleButton {
189        self.click = Some(click);
190        self
191    }
192
193    /// XAML `IsEnabled`.
194    pub fn is_enabled(mut self, enabled: bool) -> ToggleButton {
195        self.is_enabled = enabled;
196        self
197    }
198
199    /// Sets an alternate ControlTemplate without changing the toggle behavior.
200    pub fn template(
201        mut self,
202        builder: impl Fn(
203            &mut App,
204            BuildContext,
205            Option<bool>,
206            Option<WidgetRef>,
207            ControlStates,
208        ) -> WidgetRef
209        + 'static,
210    ) -> Self {
211        self.template = Some(Rc::new(builder));
212        self
213    }
214
215    pub fn key(mut self, key: KeyRef) -> ToggleButton {
216        self.key = Some(key);
217        self
218    }
219}
220
221impl fmt::Debug for ToggleButton {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        f.debug_struct("ToggleButton")
224            .field("is_checked", &self.is_checked)
225            .field("is_three_state", &self.is_three_state)
226            .field("is_enabled", &self.is_enabled)
227            .finish_non_exhaustive()
228    }
229}
230
231impl StatelessWidget for ToggleButton {
232    fn key(&self) -> Option<&KeyRef> {
233        self.key.as_ref()
234    }
235
236    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
237        let (is_checked, content) = (self.is_checked, self.content.clone());
238        let next = next_is_checked(is_checked, self.is_three_state);
239        let (checked, click) = (self.checked.clone(), self.click.clone());
240        // `ToggleButton::OnClick`: `OnToggle`, then the base `Click`.
241        let on_click = Listener::new(move |app| {
242            checked(app, next);
243            if let Some(click) = &click {
244                click.call(app);
245            }
246        });
247        let custom_template = self.template.clone();
248        CommonStates::new(on_click, move |app, context, states| {
249            if let Some(builder) = &custom_template {
250                builder(app, context, is_checked, content.clone(), states)
251            } else {
252                template(app, context, is_checked, content.clone(), states)
253            }
254        })
255        .is_enabled(self.is_enabled)
256        .into_widget()
257    }
258}
259
260/// The `ControlTemplate` of `DefaultToggleButtonStyle` for one `IsChecked` and set of states.
261fn template(
262    app: &mut App,
263    context: BuildContext,
264    is_checked: Option<bool>,
265    content: Option<WidgetRef>,
266    states: ControlStates,
267) -> WidgetRef {
268    let resources = ThemeResources::of(app, context);
269    let brushes = toggle_button_brushes(&resources, is_checked, states.common);
270    let content = content.unwrap_or_else(|| SizedBox::shrink().into_widget());
271    toggle_button_presenter(
272        &resources,
273        brushes,
274        ToggleButtonSetters::DEFAULT,
275        content,
276        states,
277    )
278}
279
280/// The properties a style sets that `DefaultToggleButtonStyle`'s template binds.
281#[derive(Clone, Copy, Debug, PartialEq)]
282pub(crate) struct ToggleButtonSetters {
283    /// `Padding`: left, top, right, bottom; the theme's `ButtonPadding` when `None`.
284    pub(crate) padding: Option<[f64; 4]>,
285    /// `HorizontalContentAlignment`, where the content sits across the button.
286    pub(crate) horizontal_content_alignment: AlignmentGeometry,
287}
288
289impl ToggleButtonSetters {
290    /// `DefaultToggleButtonStyle`'s own.
291    pub(crate) const DEFAULT: ToggleButtonSetters = ToggleButtonSetters {
292        padding: None,
293        horizontal_content_alignment: AlignmentGeometry::CENTER,
294    };
295}
296
297/// `DefaultToggleButtonStyle`'s template in one state's `brushes`, with a style's `setters`.
298pub(crate) fn toggle_button_presenter(
299    resources: &ThemeResources,
300    brushes: ToggleButtonBrushes,
301    setters: ToggleButtonSetters,
302    content: WidgetRef,
303    states: ControlStates,
304) -> WidgetRef {
305    let text = control_text_style(
306        resources,
307        resources.control_content_theme_font_size,
308        FontWeight::W400,
309        brushes.foreground,
310    );
311    // `ContentPresenter`: `VerticalContentAlignment` is Center.
312    let label = Align::new()
313        .alignment(setters.horizontal_content_alignment)
314        .width_factor(1.0)
315        .height_factor(1.0)
316        .child(DefaultTextStyle::new(text, content))
317        .into_widget();
318    let padding = setters.padding.unwrap_or(resources.button_padding);
319    let border_thickness = resources.toggle_button_border_theme_thickness[0];
320    let corner_radius = resources.control_corner_radius[0];
321    let presenter = ColorTransition::new(
322        brushes.background,
323        resources.control_faster_animation_duration,
324        move |_app, background| {
325            ControlBorder::new(Brush::Solid(background), brushes.border)
326                .border_thickness(border_thickness)
327                .corner_radius(corner_radius)
328                .background_sizing(brushes.background_sizing)
329                .padding(padding)
330                .child(label.clone())
331                .into_widget()
332        },
333    );
334    FocusVisual::new(presenter, resources.theme)
335        .visible(states.focused)
336        .margin(TOGGLE_BUTTON_FOCUS_VISUAL_MARGIN)
337        .corner_radius(resources.control_corner_radius[0])
338        .into_widget()
339}