Skip to main content

waft_winui/controls/
split_button.rs

1//! SplitButton.cpp and SplitButton.xaml: separate primary and flyout actions.
2
3use crate::*;
4use std::{fmt, rc::Rc};
5use waft_embedder::{Color, FontWeight, PointerDeviceKind};
6use waft_foundation::{App, Handle, Listener, OptionRetained, Ref};
7use waft_painting::{Alignment, EdgeInsetsGeometry};
8use waft_services::{HardwareKeyboard, KeyEvent, LogicalKeyboardKey};
9use waft_widgets::*;
10
11/// A primary action and a separate button that opens an associated flyout.
12#[derive(Clone)]
13pub struct SplitButton {
14    /// Content displayed by PrimaryButton.
15    pub content: WidgetRef,
16
17    /// Primary action, used for pointer activation and Space/Enter.
18    pub click: Listener,
19
20    /// Flyout opened by SecondaryButton, F4 or Alt+Down.
21    pub flyout: Option<Ref<Flyout>>,
22
23    /// Enables both actions and keyboard focus.
24    pub is_enabled: bool,
25
26    /// Includes this control in sequential keyboard traversal.
27    pub is_tab_stop: bool,
28
29    /// Optional caller-owned focus identity for the whole control.
30    pub focus_node: Option<FocusNodeRef>,
31
32    /// Identity across parent rebuilds.
33    pub key: Option<KeyRef>,
34}
35
36impl fmt::Debug for SplitButton {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_struct("SplitButton")
39            .field("is_enabled", &self.is_enabled)
40            .field("flyout", &self.flyout)
41            .finish_non_exhaustive()
42    }
43}
44
45impl SplitButton {
46    /// Creates the source primary/secondary button template.
47    #[cfg_attr(debug_assertions, track_caller)]
48    pub fn new<K>(content: impl IntoWidget<K>, click: Listener) -> Self {
49        Self {
50            content: content.into_widget(),
51            click,
52            flyout: None,
53            is_enabled: true,
54            is_tab_stop: true,
55            focus_node: None,
56            key: None,
57        }
58    }
59
60    /// Creates a split button with a text label.
61    pub fn text(text: impl Into<String>, click: Listener) -> Self {
62        Self::new(Text::new(text), click)
63    }
64
65    /// Sets the associated flyout without changing its ownership.
66    pub fn flyout(mut self, flyout: Ref<Flyout>) -> Self {
67        self.flyout = Some(flyout);
68        self
69    }
70
71    /// Enables or disables both actions.
72    pub fn is_enabled(mut self, enabled: bool) -> Self {
73        self.is_enabled = enabled;
74        self
75    }
76
77    /// Sets whether Tab visits the control.
78    pub fn is_tab_stop(mut self, value: bool) -> Self {
79        self.is_tab_stop = value;
80        self
81    }
82
83    /// Supplies a caller-owned focus node.
84    pub fn focus_node(mut self, node: FocusNodeRef) -> Self {
85        self.focus_node = Some(node);
86        self
87    }
88
89    /// Sets the widget's identity.
90    pub fn key(mut self, key: KeyRef) -> Self {
91        self.key = Some(key);
92        self
93    }
94}
95
96/// CommonStates shared by SplitButton and ToggleSplitButton.
97#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98enum SplitButtonVisualState {
99    Normal,
100    Disabled,
101    FlyoutOpen,
102    TouchPressed,
103    PrimaryPointerOver,
104    PrimaryPressed,
105    SecondaryPointerOver,
106    SecondaryPressed,
107}
108
109/// Pointer and keyboard state shared by the two source buttons.
110pub(crate) struct SplitButtonState {
111    /// Native state identity.
112    state: StateData<SplitButtonPresenter>,
113
114    /// Focus identity for the whole control, while internal buttons are not tab stops.
115    focus: Option<FocusNodeRef>,
116
117    /// Whether this state must dispose the focus node.
118    owns_focus: bool,
119
120    /// Pointer type most recently observed by either button.
121    last_pointer: PointerDeviceKind,
122
123    /// Space, Enter or gamepad accept is held.
124    key_down: bool,
125
126    /// IsPressed of PrimaryButton.
127    primary_pressed: bool,
128
129    /// IsPressed of SecondaryButton.
130    secondary_pressed: bool,
131
132    /// IsPointerOver of PrimaryButton.
133    primary_hovered: bool,
134
135    /// IsPointerOver of SecondaryButton.
136    secondary_hovered: bool,
137
138    /// Native focus-highlight visibility.
139    focused: bool,
140
141    /// Opening context beneath FlyoutTarget for the entire split button.
142    target: Option<BuildContext>,
143}
144
145impl StatelessWidget for SplitButton {
146    fn key(&self) -> Option<&KeyRef> {
147        self.key.as_ref()
148    }
149
150    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
151        SplitButtonPresenter {
152            button: self.clone(),
153            is_checked: false,
154        }
155        .into_widget()
156    }
157}
158
159/// Both source classes use the same template and input state, with a checked-state override.
160#[derive(Clone, Debug)]
161pub(crate) struct SplitButtonPresenter {
162    /// Shared content, activation and focus configuration.
163    pub(crate) button: SplitButton,
164
165    /// ToggleSplitButton::InternalIsChecked; false for an ordinary SplitButton.
166    pub(crate) is_checked: bool,
167}
168
169impl std::ops::Deref for SplitButtonPresenter {
170    type Target = SplitButton;
171
172    fn deref(&self) -> &Self::Target {
173        &self.button
174    }
175}
176
177impl StatefulWidget for SplitButtonPresenter {
178    type State = SplitButtonState;
179
180    fn create_state(&self) -> Self::State {
181        SplitButtonState {
182            state: StateData::new(),
183            focus: None,
184            owns_focus: false,
185            last_pointer: PointerDeviceKind::Mouse,
186            key_down: false,
187            primary_pressed: false,
188            secondary_pressed: false,
189            primary_hovered: false,
190            secondary_hovered: false,
191            focused: false,
192            target: None,
193        }
194    }
195}
196
197impl SplitButtonState {
198    /// SplitButton::UpdateVisualStates chooses interaction state before checked colors.
199    fn visual_state(self: Handle<Self>, app: &App) -> SplitButtonVisualState {
200        use SplitButtonVisualState::*;
201        let widget = self.widget(app);
202        let state = app.get(self);
203        if !widget.is_enabled {
204            Disabled
205        } else if widget
206            .flyout
207            .handle()
208            .is_some_and(|flyout| flyout.is_open(app))
209        {
210            FlyoutOpen
211        } else if state.last_pointer == PointerDeviceKind::Touch || state.key_down {
212            if state.primary_pressed || state.secondary_pressed || state.key_down {
213                TouchPressed
214            } else {
215                Normal
216            }
217        } else if state.primary_pressed {
218            PrimaryPressed
219        } else if state.primary_hovered {
220            PrimaryPointerOver
221        } else if state.secondary_pressed {
222            SecondaryPressed
223        } else if state.secondary_hovered {
224            SecondaryPointerOver
225        } else {
226            Normal
227        }
228    }
229
230    /// SplitButton::OpenFlyout uses this per-opening override and Auto show mode.
231    fn open_flyout(self: Handle<Self>, app: &mut App) {
232        if let Some(flyout) = self.widget(app).flyout.handle() {
233            flyout.show_at_with_options(
234                app,
235                app.get(self).target.unwrap(),
236                FlyoutShowOptions {
237                    placement: Some(FlyoutPlacementMode::BottomEdgeAlignedLeft),
238                    ..Default::default()
239                },
240            );
241        }
242    }
243
244    /// SplitButton key-down visuals and key-up activation/opening rules.
245    fn on_key(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
246        let key = event.logical_key();
247        let activation = matches!(
248            key,
249            LogicalKeyboardKey::SPACE
250                | LogicalKeyboardKey::ENTER
251                | LogicalKeyboardKey::NUMPAD_ENTER
252                | LogicalKeyboardKey::GAME_BUTTON_A
253        );
254        if matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_)) {
255            if activation {
256                self.set_state(app, |state| state.key_down = true);
257                return KeyEventResult::Handled;
258            }
259        } else if activation {
260            self.set_state(app, |state| state.key_down = false);
261            let widget = self.widget(app).clone();
262            if widget.is_enabled {
263                widget.click.call(app);
264                return KeyEventResult::Handled;
265            }
266        } else if self.widget(app).is_enabled
267            && (key == LogicalKeyboardKey::F4
268                || (key == LogicalKeyboardKey::ARROW_DOWN
269                    && HardwareKeyboard::instance(app).is_alt_pressed(app)))
270        {
271            self.open_flyout(app);
272            return KeyEventResult::Handled;
273        }
274        KeyEventResult::Ignored
275    }
276
277    /// Tracks source IsPressed changes from the internal buttons.
278    fn pressed_changed(self: Handle<Self>, app: &mut App, primary: bool, pressed: bool) {
279        let old = if primary {
280            app.get(self).primary_pressed
281        } else {
282            app.get(self).secondary_pressed
283        };
284        if old != pressed {
285            self.set_state(app, |state| {
286                if primary {
287                    state.primary_pressed = pressed;
288                } else {
289                    state.secondary_pressed = pressed;
290                }
291            });
292        }
293    }
294
295    /// Tracks source pointer device changes on enter, exit, press, release and cancellation.
296    fn pointer_kind(self: Handle<Self>, app: &mut App, kind: PointerDeviceKind) {
297        if app.get(self).last_pointer != kind {
298            self.set_state(app, |state| state.last_pointer = kind);
299        }
300    }
301
302    /// Creates or attaches the whole-control focus node.
303    fn attach_focus(self: Handle<Self>, app: &mut App) {
304        let external = self.widget(app).focus_node.clone();
305        let node = external
306            .clone()
307            .unwrap_or_else(|| FocusNode::new(app).into_erased());
308        node.set_skip_traversal(app, !self.widget(app).is_tab_stop);
309        node.set_on_key_event(
310            app,
311            Some(Rc::new(move |app, _, event| self.on_key(app, event))),
312        );
313        app.get_mut(self).focus = Some(node);
314        app.get_mut(self).owns_focus = external.is_none();
315    }
316
317    /// Builds one internal Button with the source template's unstyled content presenter.
318    fn button(
319        self: Handle<Self>,
320        r: &ThemeResources,
321        app: &mut App,
322        primary: bool,
323        foreground: Color,
324        disabled_background: Color,
325    ) -> WidgetRef {
326        let widget = self.widget(app).clone();
327        let content = if primary {
328            widget.content.clone()
329        } else {
330            SizedBox::new()
331                .width(12.0)
332                .height(12.0)
333                .child(
334                    Center::new().child(
335                        FontIcon::symbol(FluentSymbol::ChevronDown)
336                            .font_size(8.0)
337                            .foreground(foreground),
338                    ),
339                )
340                .into_widget()
341        };
342        let padding = r.split_button_padding;
343        let text_style = control_text_style(
344            r,
345            r.control_content_theme_font_size,
346            FontWeight::NORMAL,
347            foreground,
348        );
349        let button = CommonStates::new(
350            Listener::new(move |app| {
351                if primary {
352                    self.widget(app).click.clone().call(app);
353                } else {
354                    self.open_flyout(app);
355                }
356            }),
357            move |_, _, states| {
358                let content = DefaultTextStyle::new(text_style.clone(), content.clone());
359                let presenter = if primary {
360                    Padding::new(EdgeInsetsGeometry::from_ltrb(
361                        padding[0], padding[1], padding[2], padding[3],
362                    ))
363                    .child(
364                        Center::new()
365                            .width_factor(1.0)
366                            .height_factor(1.0)
367                            .child(content),
368                    )
369                    .into_widget()
370                } else {
371                    Padding::new(EdgeInsetsGeometry::from_ltrb(0.0, 0.0, 12.0, 0.0))
372                        .child(
373                            Align::new()
374                                .alignment(Alignment::CENTER_RIGHT.into())
375                                .width_factor(1.0)
376                                .height_factor(1.0)
377                                .child(content),
378                        )
379                        .into_widget()
380                };
381                Grid::new()
382                    .background(Brush::Solid(if states.common == CommonState::Disabled {
383                        disabled_background
384                    } else {
385                        Color::new(0)
386                    }))
387                    .children([presenter])
388                    .into_widget()
389            },
390        )
391        .is_enabled(widget.is_enabled)
392        .is_tab_stop(false)
393        .pressed_changed(move |app, pressed| self.pressed_changed(app, primary, pressed));
394        let button = MouseRegion::new()
395            .on_enter(Rc::new(move |app, event| {
396                self.pointer_kind(app, event.kind);
397                self.set_state(app, |state| {
398                    if primary {
399                        state.primary_hovered = true;
400                    } else {
401                        state.secondary_hovered = true;
402                    }
403                });
404            }))
405            .on_exit(Rc::new(move |app, event| {
406                self.pointer_kind(app, event.kind);
407                self.set_state(app, |state| {
408                    if primary {
409                        state.primary_hovered = false;
410                    } else {
411                        state.secondary_hovered = false;
412                    }
413                });
414            }))
415            .child(button);
416        waft_widgets::Listener::new()
417            .on_pointer_down(Rc::new(move |app, event| {
418                self.pointer_kind(app, event.kind)
419            }))
420            .on_pointer_up(Rc::new(move |app, event| {
421                self.pointer_kind(app, event.kind)
422            }))
423            .on_pointer_cancel(Rc::new(move |app, event| {
424                self.pointer_kind(app, event.kind)
425            }))
426            .child(button)
427            .into_widget()
428    }
429
430    /// RootGrid layers appear in the same order as SplitButton.xaml.
431    fn template(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
432        let theme = ThemeResources::of(app, context);
433        let r = &theme;
434        let state = self.visual_state(app);
435        let mut primary_fill = r.split_button_background;
436        let mut secondary_fill = r.split_button_background;
437        let mut primary_foreground = r.split_button_foreground;
438        let mut secondary_foreground = r.split_button_foreground_secondary;
439        let mut primary_border = Brush::ControlElevation(r.split_button_border_brush);
440        let mut secondary_border = primary_border;
441        use SplitButtonVisualState::*;
442        match state {
443            Disabled => {
444                primary_fill = Color::new(0);
445                secondary_fill = Color::new(0);
446                primary_foreground = r.split_button_foreground_disabled;
447                secondary_foreground = r.split_button_foreground_disabled;
448                primary_border = Brush::Solid(r.split_button_border_brush_disabled);
449                secondary_border = primary_border;
450            }
451            FlyoutOpen | TouchPressed => {
452                primary_fill = r.split_button_background_pressed;
453                secondary_fill = primary_fill;
454                primary_foreground = r.split_button_foreground_pressed;
455                secondary_foreground = r.split_button_foreground_secondary_pressed;
456                primary_border = Brush::Solid(r.split_button_border_brush_pressed);
457                secondary_border = primary_border;
458            }
459            PrimaryPointerOver => {
460                primary_fill = r.split_button_background_pointer_over;
461                primary_foreground = r.split_button_foreground_pointer_over;
462            }
463            PrimaryPressed => {
464                primary_fill = r.split_button_background_pressed;
465                primary_foreground = r.split_button_foreground_pressed;
466                primary_border = Brush::Solid(r.split_button_border_brush_pressed);
467            }
468            SecondaryPointerOver => {
469                secondary_fill = r.split_button_background_pointer_over;
470                secondary_foreground = r.split_button_foreground_pointer_over;
471            }
472            SecondaryPressed => {
473                secondary_fill = r.split_button_background_pressed;
474                secondary_foreground = r.split_button_foreground_secondary_pressed;
475                secondary_border = Brush::Solid(r.split_button_border_brush_pressed);
476            }
477            Normal => {}
478        }
479        let mut divider = r.split_button_border_brush_divider;
480        if self.widget(app).is_checked && state != Disabled {
481            primary_fill = r.split_button_background_checked;
482            secondary_fill = primary_fill;
483            primary_foreground = r.split_button_foreground_checked;
484            secondary_foreground = primary_foreground;
485            primary_border = Brush::ControlElevation(r.split_button_border_brush_checked);
486            secondary_border = primary_border;
487            divider = r.split_button_border_brush_checked_divider;
488
489            match state {
490                FlyoutOpen | TouchPressed => {
491                    primary_fill = r.split_button_background_checked_pressed;
492                    secondary_fill = primary_fill;
493                    primary_foreground = r.split_button_foreground_checked_pressed;
494                    secondary_foreground = primary_foreground;
495                    primary_border = Brush::Solid(r.split_button_border_brush_checked_pressed);
496                    secondary_border = primary_border;
497                }
498                PrimaryPointerOver => {
499                    primary_fill = r.split_button_background_checked_pointer_over;
500                    primary_foreground = r.split_button_foreground_checked_pointer_over;
501                }
502                PrimaryPressed => {
503                    primary_fill = r.split_button_background_checked_pressed;
504                    primary_foreground = r.split_button_foreground_checked_pressed;
505                }
506                SecondaryPointerOver => {
507                    secondary_fill = r.split_button_background_checked_pointer_over;
508                    secondary_foreground = r.split_button_foreground_checked_pointer_over;
509                }
510                SecondaryPressed => {
511                    secondary_fill = r.split_button_background_checked_pressed;
512                    secondary_foreground = r.split_button_foreground_checked_pressed;
513                }
514                Normal | Disabled => {}
515            }
516        }
517        let primary = self.button(
518            &theme,
519            app,
520            true,
521            primary_foreground,
522            r.split_button_background_disabled,
523        );
524        let secondary = self.button(
525            &theme,
526            app,
527            false,
528            secondary_foreground,
529            r.split_button_background_disabled,
530        );
531        let key_down = app.get(self).key_down;
532        let root = Grid::new()
533            .background(Brush::Solid(Color::new(0)))
534            .corner_radius_corners(r.control_corner_radius)
535            .column_definitions([
536                ColumnDefinition::new(GridLength::STAR)
537                    .min_width(r.split_button_primary_button_size),
538                ColumnDefinition::new(GridLength::pixel(1.0)),
539                ColumnDefinition::new(GridLength::pixel(r.split_button_secondary_button_size)),
540            ])
541            .children([
542                GridCell::new(Grid::new().background(Brush::Solid(primary_fill)))
543                    .column_span(2)
544                    .into_widget(),
545                GridCell::new(Grid::new().background(Brush::Solid(divider)))
546                    .column(1)
547                    .into_widget(),
548                GridCell::new(Grid::new().background(Brush::Solid(secondary_fill)))
549                    .column(2)
550                    .into_widget(),
551                GridCell::new(primary).into_widget(),
552                GridCell::new(secondary)
553                    .column(if key_down { 0 } else { 2 })
554                    .column_span(if key_down { 3 } else { 1 })
555                    .into_widget(),
556                GridCell::new(
557                    Grid::new()
558                        .border_brush(primary_border)
559                        .border_thickness_ltrb([1.0, 1.0, 0.0, 1.0])
560                        .corner_radius_corners([4.0, 0.0, 0.0, 4.0]),
561                )
562                .into_widget(),
563                GridCell::new(
564                    Grid::new()
565                        .border_brush(secondary_border)
566                        .border_thickness_ltrb([0.0, 1.0, 1.0, 1.0])
567                        .corner_radius_corners([0.0, 4.0, 4.0, 0.0]),
568                )
569                .column(2)
570                .into_widget(),
571            ]);
572        FocusVisual::new(root, theme.theme)
573            .visible(app.get(self).focused)
574            .margin([-1.0; 4])
575            .corner_radius(r.control_corner_radius[0])
576            .into_widget()
577    }
578}
579
580impl State for SplitButtonState {
581    type Widget = SplitButtonPresenter;
582    waft_widgets::state_accessors!();
583
584    fn init_state(self: Handle<Self>, app: &mut App) {
585        crate::InputDevice::initialize(app);
586        self.attach_focus(app);
587    }
588
589    fn did_update_widget(self: Handle<Self>, app: &mut App, old: &SplitButtonPresenter) {
590        if !self.widget(app).is_enabled {
591            app.get_mut(self).primary_pressed = false;
592            app.get_mut(self).secondary_pressed = false;
593        }
594        if old.focus_node != self.widget(app).focus_node {
595            let node = app.get(self).focus.clone().unwrap();
596            node.set_on_key_event(app, None);
597            if app.get(self).owns_focus {
598                node.dispose(app);
599            }
600            self.attach_focus(app);
601        }
602        app.get(self)
603            .focus
604            .handle()
605            .unwrap()
606            .set_skip_traversal(app, !self.widget(app).is_tab_stop);
607    }
608
609    fn dispose(self: Handle<Self>, app: &mut App) {
610        let node = app.get(self).focus.clone().unwrap();
611        if app.get(self).owns_focus {
612            node.dispose(app);
613        } else {
614            node.set_on_key_event(app, None);
615        }
616    }
617
618    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
619        let widget = self.widget(app).clone();
620        let content = if let Some(flyout) = widget.flyout.clone() {
621            ListenableBuilder::new(Rc::new(flyout), move |app, context, _| {
622                self.template(app, context)
623            })
624            .into_widget()
625        } else {
626            self.template(app, context)
627        };
628        let content = FocusableActionDetector::new(content)
629            .focus_node(app.get(self).focus.clone().unwrap())
630            .enabled(widget.is_enabled)
631            .on_focus_change(move |app, focused| {
632                let value = focused && crate::FocusState::current(app).shows_focus_visual();
633                self.set_state(app, |state| state.focused = value)
634            });
635        let content = content.into_widget();
636        FlyoutTarget::new(Builder::new(move |app, context| {
637            app.get_mut(self).target = Some(context);
638            content.clone()
639        }))
640        .into_widget()
641    }
642}