Skip to main content

waft_winui/controls/command_bar/
app_bar_toggle_button.rs

1//! XAML `AppBarToggleButton` with the `DefaultAppBarToggleButtonStyle` of `AppBarToggleButton_themeresources.xaml`, and `AppBarToggleButton_Partial.cpp` with `AppBarButtonHelpers.h`.
2//!
3//! The template is `Root` holding `AppBarToggleButtonInnerBorder` under `ContentRoot`, a grid of two columns and two rows: `OverflowCheckGlyph`, `ContentViewbox`, `TextLabel`, `OverflowTextLabel` and `KeyboardAcceleratorTextLabel`. `ApplicationViewStates` is the button's (see [`ApplicationViewState`]) without the toggle-button variants. `CommonStates` holds the unchecked and `Checked*` states `ToggleButton::ChangeVisualState` picks and the `Overflow*` states `AppBarToggleButton::ChangeVisualState` then picks for an enabled button in the overflow; it has no `Indeterminate*` states, so an indeterminate button keeps the look of the state it was last in, and a later editor must keep that memory in the widget's state.
4
5use super::app_bar_button::{
6    content_root_min_height, content_viewbox, inner_border, inner_border_margin,
7    keyboard_accelerator_text_label, overflow_text_label, root, with_tool_tip,
8};
9use super::element::{
10    ApplicationViewState, CommandBarLabelPosition, ElementHost, ElementPresentation,
11};
12use crate::{
13    BackgroundSizing, Brush, ColumnDefinition, CommonState, CommonStates, ControlStates,
14    FluentSymbol, FontIcon, Grid, GridCell, GridLength, InputDevice, Margin, RowDefinition,
15    ThemeResources, control_text_style, next_is_checked,
16};
17use std::{fmt, rc::Rc};
18use waft_embedder::{Color, FontWeight, TextAlign};
19use waft_foundation::{App, Handle, Listener};
20use waft_painting::AlignmentGeometry;
21use waft_rendering::BoxConstraints;
22use waft_widgets::*;
23
24/// Receives the `IsChecked` value a toggle asks for: XAML `Checked`, `Unchecked` and `Indeterminate`.
25pub type AppBarToggleButtonCheckedHandler = Rc<dyn Fn(&mut App, Option<bool>)>;
26
27/// XAML `AppBarToggleButton`: a command that keeps a checked state, for a `CommandBar`.
28#[derive(Clone)]
29pub struct AppBarToggleButton {
30    /// `Label`.
31    pub label: String,
32    /// `IsChecked`; `None` is indeterminate.
33    pub is_checked: Option<bool>,
34    /// Asked for the next `IsChecked` on each click; the button shows the value it is given.
35    pub checked: AppBarToggleButtonCheckedHandler,
36    /// `Icon`.
37    pub icon: Option<WidgetRef>,
38    /// `LabelPosition`.
39    pub label_position: CommandBarLabelPosition,
40    /// `IsThreeState`: a click on a checked button makes it indeterminate.
41    pub is_three_state: bool,
42    /// `IsEnabled`.
43    pub is_enabled: bool,
44    /// `DynamicOverflowOrder`.
45    pub dynamic_overflow_order: i32,
46    /// `KeyboardAcceleratorTextOverride`.
47    pub keyboard_accelerator_text_override: String,
48    pub(crate) presentation: ElementPresentation,
49    pub(crate) host: Option<ElementHost>,
50    /// Identity retained across parent rebuilds.
51    pub key: Option<KeyRef>,
52}
53
54impl AppBarToggleButton {
55    /// Creates a toggle button with a `Label`, its `IsChecked` and the callback asked for the next value.
56    pub fn new(
57        label: impl Into<String>,
58        is_checked: Option<bool>,
59        checked: impl Fn(&mut App, Option<bool>) + 'static,
60    ) -> Self {
61        Self {
62            label: label.into(),
63            is_checked,
64            checked: Rc::new(checked),
65            icon: None,
66            label_position: CommandBarLabelPosition::Default,
67            is_three_state: false,
68            is_enabled: true,
69            dynamic_overflow_order: 0,
70            keyboard_accelerator_text_override: String::new(),
71            presentation: ElementPresentation::default(),
72            host: None,
73            key: None,
74        }
75    }
76
77    /// Sets the XAML `Icon`.
78    #[cfg_attr(debug_assertions, track_caller)]
79    pub fn icon<K>(mut self, icon: impl IntoWidget<K>) -> Self {
80        self.icon = Some(icon.into_widget());
81        self
82    }
83
84    /// Sets the XAML `LabelPosition`.
85    pub fn label_position(mut self, position: CommandBarLabelPosition) -> Self {
86        self.label_position = position;
87        self
88    }
89
90    /// Sets the XAML `IsThreeState`.
91    pub fn is_three_state(mut self, value: bool) -> Self {
92        self.is_three_state = value;
93        self
94    }
95
96    /// Sets the XAML `IsEnabled`.
97    pub fn is_enabled(mut self, enabled: bool) -> Self {
98        self.is_enabled = enabled;
99        self
100    }
101
102    /// Sets the XAML `DynamicOverflowOrder`.
103    pub fn dynamic_overflow_order(mut self, order: i32) -> Self {
104        self.dynamic_overflow_order = order;
105        self
106    }
107
108    /// Sets the XAML `KeyboardAcceleratorTextOverride`.
109    pub fn keyboard_accelerator_text_override(mut self, text: impl Into<String>) -> Self {
110        self.keyboard_accelerator_text_override = text.into();
111        self
112    }
113
114    /// Sets the identity retained across rebuilds.
115    pub fn key(mut self, key: KeyRef) -> Self {
116        self.key = Some(key);
117        self
118    }
119}
120
121impl fmt::Debug for AppBarToggleButton {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        f.debug_struct("AppBarToggleButton")
124            .field("label", &self.label)
125            .field("is_checked", &self.is_checked)
126            .field("is_three_state", &self.is_three_state)
127            .field("is_enabled", &self.is_enabled)
128            .field("dynamic_overflow_order", &self.dynamic_overflow_order)
129            .finish_non_exhaustive()
130    }
131}
132
133impl StatefulWidget for AppBarToggleButton {
134    type State = AppBarToggleButtonState;
135
136    fn key(&self) -> Option<&KeyRef> {
137        self.key.as_ref()
138    }
139
140    fn create_state(&self) -> AppBarToggleButtonState {
141        AppBarToggleButtonState {
142            state: StateData::new(),
143            last_state: ToggleCommonState::Normal,
144        }
145    }
146}
147
148/// The `CommonStates` state the template is in, kept for an indeterminate button.
149pub struct AppBarToggleButtonState {
150    state: StateData<AppBarToggleButton>,
151    last_state: ToggleCommonState,
152}
153
154impl State for AppBarToggleButtonState {
155    type Widget = AppBarToggleButton;
156    waft_widgets::state_accessors!();
157
158    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
159        let widget = self.widget(app).clone();
160        let next = next_is_checked(widget.is_checked, widget.is_three_state);
161        let (checked, host) = (widget.checked.clone(), widget.host.clone());
162        // `AppBarToggleButton::OnClick`: the bar closes, then `ToggleButton::OnClick` toggles.
163        let on_click = Listener::new(move |app| {
164            if let Some(host) = &host {
165                host.executed.call(app);
166            }
167            checked(app, next);
168        });
169        let template_widget = widget.clone();
170        let mut states = CommonStates::new(on_click, move |app, context, states| {
171            let state = ToggleCommonState::of(
172                &template_widget.presentation,
173                template_widget.is_checked,
174                states,
175                app.get(self).last_state,
176            );
177            app.get_mut(self).last_state = state.base;
178            template(app, context, &template_widget, state.shown, states)
179        })
180        .is_enabled(widget.is_enabled);
181        if let Some(host) = &widget.host {
182            states = states.focus_node(host.focus_node.clone());
183        }
184        with_tool_tip(
185            states.into_widget(),
186            &widget.label,
187            &widget.keyboard_accelerator_text_override,
188            &widget.presentation,
189        )
190    }
191}
192
193/// The template's `CommonStates`.
194#[derive(Clone, Copy, Debug, PartialEq, Eq)]
195enum ToggleCommonState {
196    Normal,
197    PointerOver,
198    Pressed,
199    Disabled,
200    Checked,
201    CheckedPointerOver,
202    CheckedPressed,
203    CheckedDisabled,
204    OverflowNormal,
205    OverflowPointerOver,
206    OverflowPressed,
207    OverflowChecked,
208    OverflowCheckedPointerOver,
209    OverflowCheckedPressed,
210}
211
212/// The state `ToggleButton::ChangeVisualState` leaves (`base`) and the one shown after `AppBarToggleButton::ChangeVisualState` (`shown`).
213struct ResolvedToggleState {
214    base: ToggleCommonState,
215    shown: ToggleCommonState,
216}
217
218impl ToggleCommonState {
219    fn of(
220        presentation: &ElementPresentation,
221        is_checked: Option<bool>,
222        states: ControlStates,
223        last: ToggleCommonState,
224    ) -> ResolvedToggleState {
225        use ToggleCommonState::*;
226        let base = match (is_checked, states.common) {
227            // The template has no `Indeterminate*` states: the group stays where it was.
228            (None, _) => last,
229            (Some(true), CommonState::Disabled) => CheckedDisabled,
230            (Some(true), CommonState::Pressed) => CheckedPressed,
231            (Some(true), CommonState::PointerOver) => CheckedPointerOver,
232            (Some(true), CommonState::Normal) => Checked,
233            (Some(false), CommonState::Disabled) => Disabled,
234            (Some(false), CommonState::Pressed) => Pressed,
235            (Some(false), CommonState::PointerOver) => PointerOver,
236            (Some(false), CommonState::Normal) => Normal,
237        };
238        let shown = if !presentation.use_overflow_style || states.common == CommonState::Disabled {
239            base
240        } else {
241            match (is_checked == Some(true), states.common) {
242                (true, CommonState::Pressed) => OverflowCheckedPressed,
243                (true, CommonState::PointerOver) => OverflowCheckedPointerOver,
244                (true, _) => OverflowChecked,
245                (false, CommonState::Pressed) => OverflowPressed,
246                (false, CommonState::PointerOver) => OverflowPointerOver,
247                (false, _) => OverflowNormal,
248            }
249        };
250        ResolvedToggleState { base, shown }
251    }
252}
253
254/// The values one `CommonStates` state sets, the style's where it sets none.
255#[derive(Clone, Copy, Debug)]
256struct ToggleBrushes {
257    background: Color,
258    border: Brush,
259    background_sizing: BackgroundSizing,
260    /// `Content.Foreground`.
261    content: Color,
262    /// `TextLabel.Foreground`.
263    label: Color,
264    /// `OverflowCheckGlyph.Foreground`.
265    glyph: Color,
266    /// `OverflowTextLabel.Foreground`.
267    overflow_label: Color,
268    /// `KeyboardAcceleratorTextLabel.Foreground`.
269    accelerator: Color,
270    /// `OverflowCheckGlyph.Opacity`.
271    glyph_opacity: f64,
272}
273
274fn brushes(r: &ThemeResources, state: ToggleCommonState) -> ToggleBrushes {
275    use ToggleCommonState::*;
276    let style = ToggleBrushes {
277        background: r.app_bar_toggle_button_background,
278        border: Brush::Solid(r.app_bar_toggle_button_border_brush),
279        background_sizing: BackgroundSizing::InnerBorderEdge,
280        content: r.app_bar_toggle_button_foreground,
281        label: r.app_bar_toggle_button_foreground,
282        glyph: r.app_bar_toggle_button_check_glyph_foreground,
283        overflow_label: r.app_bar_toggle_button_foreground,
284        accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground,
285        glyph_opacity: 0.0,
286    };
287    let checked = |background, border, content, accelerator| ToggleBrushes {
288        background,
289        border,
290        background_sizing: BackgroundSizing::OuterBorderEdge,
291        content,
292        label: content,
293        accelerator,
294        glyph_opacity: 1.0,
295        ..style
296    };
297    match state {
298        Normal | OverflowNormal => style,
299        PointerOver => ToggleBrushes {
300            background: r.app_bar_toggle_button_background_pointer_over,
301            border: Brush::Solid(r.app_bar_toggle_button_border_brush_pointer_over),
302            content: r.app_bar_toggle_button_foreground_pointer_over,
303            label: r.app_bar_toggle_button_foreground_pointer_over,
304            glyph: r.app_bar_toggle_button_overflow_label_foreground_pointer_over,
305            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_pointer_over,
306            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_pointer_over,
307            ..style
308        },
309        Pressed => ToggleBrushes {
310            background: r.app_bar_toggle_button_background_pressed,
311            border: Brush::Solid(r.app_bar_toggle_button_border_brush_pressed),
312            content: r.app_bar_toggle_button_foreground_pressed,
313            label: r.app_bar_toggle_button_foreground_pressed,
314            glyph: r.app_bar_toggle_button_overflow_label_foreground_pressed,
315            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_pressed,
316            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_pressed,
317            ..style
318        },
319        Disabled => ToggleBrushes {
320            background: r.app_bar_toggle_button_background_disabled,
321            border: Brush::Solid(r.app_bar_toggle_button_border_brush_disabled),
322            content: r.app_bar_toggle_button_foreground_disabled,
323            label: r.app_bar_toggle_button_foreground_disabled,
324            glyph: r.app_bar_toggle_button_overflow_label_foreground_disabled,
325            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_disabled,
326            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_disabled,
327            ..style
328        },
329        Checked => checked(
330            r.app_bar_toggle_button_background_checked,
331            Brush::ControlElevation(r.app_bar_toggle_button_border_brush_checked),
332            r.app_bar_toggle_button_foreground_checked,
333            r.app_bar_toggle_button_keyboard_accelerator_text_foreground_checked,
334        ),
335        CheckedPointerOver => ToggleBrushes {
336            glyph: r.app_bar_toggle_button_overflow_label_foreground_checked_pointer_over,
337            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_checked_pointer_over,
338            ..checked(
339                r.app_bar_toggle_button_background_checked_pointer_over,
340                Brush::ControlElevation(r.app_bar_toggle_button_border_brush_checked_pointer_over),
341                r.app_bar_toggle_button_foreground_checked_pointer_over,
342                r.app_bar_toggle_button_keyboard_accelerator_text_foreground_checked_pointer_over,
343            )
344        },
345        CheckedPressed => ToggleBrushes {
346            glyph: r.app_bar_toggle_button_overflow_label_foreground_checked_pressed,
347            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_checked_pressed,
348            ..checked(
349                r.app_bar_toggle_button_background_checked_pressed,
350                Brush::Solid(r.app_bar_toggle_button_border_brush_checked_pressed),
351                r.app_bar_toggle_button_foreground_checked_pressed,
352                r.app_bar_toggle_button_keyboard_accelerator_text_foreground_checked_pressed,
353            )
354        },
355        CheckedDisabled => ToggleBrushes {
356            glyph: r.app_bar_toggle_button_overflow_label_foreground_checked_disabled,
357            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_checked_disabled,
358            ..checked(
359                r.app_bar_toggle_button_background_checked_disabled,
360                Brush::Solid(r.app_bar_toggle_button_border_brush_checked_disabled),
361                r.app_bar_toggle_button_foreground_checked_disabled,
362                r.app_bar_toggle_button_keyboard_accelerator_text_foreground_checked_disabled,
363            )
364        },
365        OverflowPointerOver => ToggleBrushes {
366            background: r.app_bar_toggle_button_background_high_light_overlay_pointer_over,
367            border: Brush::Solid(r.app_bar_toggle_button_border_brush_pointer_over),
368            content: r.app_bar_toggle_button_foreground_pointer_over,
369            label: r.app_bar_toggle_button_foreground_pointer_over,
370            glyph: r.app_bar_toggle_button_check_glyph_foreground_pointer_over,
371            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_pointer_over,
372            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_pointer_over,
373            ..style
374        },
375        OverflowPressed => ToggleBrushes {
376            background: r.app_bar_toggle_button_background_high_light_overlay_pressed,
377            border: Brush::Solid(r.app_bar_toggle_button_border_brush_pressed),
378            content: r.app_bar_toggle_button_foreground_pressed,
379            label: r.app_bar_toggle_button_foreground_pressed,
380            glyph: r.app_bar_toggle_button_check_glyph_foreground_pressed,
381            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_pressed,
382            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_pressed,
383            ..style
384        },
385        OverflowChecked => ToggleBrushes {
386            border: Brush::ControlElevation(r.app_bar_toggle_button_border_brush_checked),
387            content: r.app_bar_toggle_button_foreground,
388            label: r.app_bar_toggle_button_foreground,
389            glyph: r.app_bar_toggle_button_foreground,
390            glyph_opacity: 1.0,
391            ..style
392        },
393        OverflowCheckedPointerOver => ToggleBrushes {
394            background: r.app_bar_toggle_button_background_high_light_overlay_checked_pointer_over,
395            content: r.app_bar_toggle_button_overflow_label_foreground_checked_pointer_over,
396            label: r.app_bar_toggle_button_foreground_checked_pointer_over,
397            glyph: r.app_bar_toggle_button_overflow_label_foreground_checked_pointer_over,
398            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_checked_pointer_over,
399            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_pointer_over,
400            glyph_opacity: 1.0,
401            ..style
402        },
403        OverflowCheckedPressed => ToggleBrushes {
404            background: r.app_bar_toggle_button_background_high_light_overlay_checked_pressed,
405            border: Brush::Solid(r.app_bar_toggle_button_border_brush_checked_pressed),
406            content: r.app_bar_toggle_button_overflow_label_foreground_checked_pressed,
407            label: r.app_bar_toggle_button_foreground_checked_pressed,
408            glyph: r.app_bar_toggle_button_overflow_label_foreground_checked_pressed,
409            overflow_label: r.app_bar_toggle_button_overflow_label_foreground_checked_pressed,
410            accelerator: r.app_bar_toggle_button_keyboard_accelerator_text_foreground_pressed,
411            glyph_opacity: 1.0,
412            ..style
413        },
414    }
415}
416
417/// The `ControlTemplate` for one view state and `CommonStates` state.
418fn template(
419    app: &mut App,
420    context: BuildContext,
421    widget: &AppBarToggleButton,
422    state: ToggleCommonState,
423    states: ControlStates,
424) -> WidgetRef {
425    let r = ThemeResources::of(app, context);
426    // `SetOverflowStyleParams` tells a toggle button only of icons and accelerator text.
427    let presentation = ElementPresentation {
428        with_toggle_buttons: false,
429        ..widget.presentation
430    };
431    let view = ApplicationViewState::of(&presentation, widget.label_position);
432    let brushes = brushes(&r, state);
433    let touch = presentation.input_mode == InputDevice::Touch;
434    let label_style =
435        |size: f64, color: Color| control_text_style(&r, size, FontWeight::NORMAL, color);
436    let mut cells = Vec::new();
437
438    // OverflowCheckGlyph
439    if view.is_overflow() {
440        let margin = if touch {
441            r.app_bar_toggle_button_overflow_check_touch_margin
442        } else {
443            r.app_bar_toggle_button_overflow_check_margin
444        };
445        cells.push(
446            GridCell::new(Margin::new(
447                margin,
448                Align::new()
449                    .alignment(AlignmentGeometry::CENTER_LEFT)
450                    .height_factor(1.0)
451                    .width_factor(1.0)
452                    .child(
453                        SizedBox::new().width(14.0).height(14.0).child(
454                            Opacity::new(brushes.glyph_opacity).child(
455                                FontIcon::symbol(FluentSymbol::Checkmark)
456                                    .font_size(16.0)
457                                    .foreground(brushes.glyph),
458                            ),
459                        ),
460                    ),
461            ))
462            .into_widget(),
463        );
464    }
465    // ContentViewbox > Content
466    if view != ApplicationViewState::Overflow {
467        let icon = widget.icon.clone().map(|icon| {
468            DefaultTextStyle::new(
469                label_style(r.control_content_theme_font_size, brushes.content),
470                icon,
471            )
472            .into_widget()
473        });
474        cells.push(GridCell::new(content_viewbox(&r, view, icon, true)).into_widget());
475    }
476    // TextLabel
477    match view {
478        ApplicationViewState::FullSize => cells.push(
479            GridCell::new(Margin::new(
480                r.app_bar_toggle_button_text_label_margin,
481                Text::new(widget.label.clone())
482                    .style(label_style(12.0, brushes.label))
483                    .text_align(TextAlign::Center),
484            ))
485            .row(1)
486            .into_widget(),
487        ),
488        ApplicationViewState::LabelOnRight => cells.push(
489            GridCell::new(Margin::new(
490                r.app_bar_toggle_button_text_label_on_right_margin,
491                Text::new(widget.label.clone())
492                    .style(label_style(12.0, brushes.label))
493                    .text_align(TextAlign::Left),
494            ))
495            .column(1)
496            .into_widget(),
497        ),
498        _ => {}
499    }
500    // OverflowTextLabel
501    if view.is_overflow() {
502        let margin = if view == ApplicationViewState::OverflowWithMenuIcons {
503            [76.0, 0.0, 12.0, 0.0]
504        } else {
505            [38.0, 0.0, 12.0, 0.0]
506        };
507        let padding = if touch {
508            r.app_bar_toggle_button_overflow_text_touch_margin
509        } else {
510            r.app_bar_toggle_button_overflow_text_label_padding
511        };
512        cells.push(
513            GridCell::new(overflow_text_label(
514                &widget.label,
515                label_style(r.control_content_theme_font_size, brushes.overflow_label),
516                margin,
517                padding,
518            ))
519            .into_widget(),
520        );
521    }
522    // KeyboardAcceleratorTextLabel
523    if let Some(cell) = keyboard_accelerator_text_label(
524        &r,
525        &presentation,
526        &widget.keyboard_accelerator_text_override,
527        brushes.accelerator,
528    ) {
529        cells.push(GridCell::new(cell).column(1).into_widget());
530    }
531
532    let content_root =
533        ConstrainedBox::new(BoxConstraints::new().min_height(content_root_min_height(&r, view)))
534            .child(
535                Grid::new()
536                    .column_definitions([
537                        ColumnDefinition::new(GridLength::STAR),
538                        ColumnDefinition::new(GridLength::AUTO),
539                    ])
540                    .row_definitions([
541                        RowDefinition::new(GridLength::AUTO),
542                        RowDefinition::new(GridLength::AUTO),
543                    ])
544                    .children(cells),
545            );
546    let inner_border = inner_border(
547        &r,
548        Brush::Solid(brushes.background),
549        brushes.border,
550        r.app_bar_toggle_button_border_theme_thickness[0],
551        brushes.background_sizing,
552        states.focused,
553    );
554    root(
555        view,
556        Margin::new(inner_border_margin(&r, view), inner_border),
557        content_root.into_widget(),
558    )
559}