Skip to main content

waft_winui/controls/
repeat_button.rs

1//! XAML `RepeatButton` with the `DefaultRepeatButtonStyle` of `RepeatButton_themeresources.xaml`.
2//!
3//! The template is one `ContentPresenter` (`x:Name="ContentPresenter"`) carrying `Background`, `BorderBrush`, `ButtonBorderThemeThickness`, `CornerRadius`, `ButtonPadding` and `Foreground`, with a `BrushTransition` of 83 ms on `Background`; the `CommonStates` storyboards swap those brushes per state.
4//!
5//! Behaviour follows `RepeatButton_Partial.cpp` and `ButtonBaseKeyProcess.h`: pointer and Space presses click immediately and start the repeat timer; Enter clicks once. The control owns its pressed state and focus node so activation keys reach its Press-mode handler before application shortcuts.
6
7use crate::{
8    BackgroundSizing, Brush, ButtonTemplate, ColorTransition, CommonState, ControlBorder,
9    ControlStates, FocusVisual, ThemeResources, control_text_style,
10};
11use std::{fmt, rc::Rc, time::Duration};
12use waft_embedder::{Color, FontWeight, Offset, PointerDeviceKind};
13use waft_foundation::{App, Handle, Listener, OptionRetained, Timer};
14use waft_gestures::{K_PRIMARY_BUTTON, PointerDownEvent, PointerMoveEvent};
15use waft_rendering::HitTestBehavior;
16use waft_services::{KeyEvent, LogicalKeyboardKey};
17use waft_widgets::Listener as PointerListener;
18use waft_widgets::*;
19
20/// The default `Delay`, 500 ms: `RepeatButton_Delay` in `DependencyProperty.cpp`.
21pub const REPEAT_BUTTON_DELAY: Duration = Duration::from_millis(500);
22/// The default `Interval`, 33 ms: `RepeatButton_Interval` in `DependencyProperty.cpp`.
23pub const REPEAT_BUTTON_INTERVAL: Duration = Duration::from_millis(33);
24/// The `FocusVisualMargin` the style sets.
25pub const REPEAT_BUTTON_FOCUS_VISUAL_MARGIN: [f64; 4] = [-3.0; 4];
26
27/// The brushes the style resolves to in one state.
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub struct RepeatButtonBrushes {
30    pub background: Color,
31    pub border: Brush,
32    pub foreground: Color,
33}
34
35/// The `{ThemeResource …}` values the `CommonStates` storyboards name for `state`.
36pub fn repeat_button_brushes(
37    resources: &ThemeResources,
38    state: CommonState,
39) -> RepeatButtonBrushes {
40    let r = resources;
41    match state {
42        CommonState::Normal => RepeatButtonBrushes {
43            background: r.repeat_button_background,
44            border: Brush::ControlElevation(r.repeat_button_border_brush),
45            foreground: r.repeat_button_foreground,
46        },
47        CommonState::PointerOver => RepeatButtonBrushes {
48            background: r.repeat_button_background_pointer_over,
49            border: Brush::ControlElevation(r.repeat_button_border_brush_pointer_over),
50            foreground: r.repeat_button_foreground_pointer_over,
51        },
52        CommonState::Pressed => RepeatButtonBrushes {
53            background: r.repeat_button_background_pressed,
54            border: Brush::Solid(r.repeat_button_border_brush_pressed),
55            foreground: r.repeat_button_foreground_pressed,
56        },
57        CommonState::Disabled => RepeatButtonBrushes {
58            background: r.repeat_button_background_disabled,
59            border: Brush::Solid(r.repeat_button_border_brush_disabled),
60            foreground: r.repeat_button_foreground_disabled,
61        },
62    }
63}
64
65/// `KeyPress::ButtonBase::IsPress` with `AcceptsReturn`: Space, Enter or GamepadA.
66fn is_press_key(key: LogicalKeyboardKey) -> bool {
67    key == LogicalKeyboardKey::SPACE
68        || key == LogicalKeyboardKey::ENTER
69        || key == LogicalKeyboardKey::NUMPAD_ENTER
70        || key == LogicalKeyboardKey::GAME_BUTTON_A
71}
72
73/// XAML `RepeatButton`: `Click` on the press, then again after `Delay` and every `Interval` while held.
74#[derive(Clone)]
75pub struct RepeatButton {
76    /// The content rendered by the button's template.
77    pub content: WidgetRef,
78
79    /// Raised on the initial press and each repeat tick.
80    pub click: Listener,
81
82    /// XAML `Delay`: the time from the press to the first repeat.
83    pub delay: Duration,
84    /// XAML `Interval`: the time between repeats.
85    pub interval: Duration,
86    /// Whether this button accepts input.
87    pub is_enabled: bool,
88
89    /// Whether keyboard traversal includes this button; defaults to true.
90    pub is_tab_stop: bool,
91
92    /// An alternate ContentPresenter template using the same input and repeat state.
93    pub template: Option<ButtonTemplate>,
94
95    /// Identity of this button in its parent's child list.
96    pub key: Option<KeyRef>,
97}
98
99impl RepeatButton {
100    /// Creates a repeating button with the default WinUI style.
101    #[cfg_attr(debug_assertions, track_caller)]
102    pub fn new<K>(content: impl IntoWidget<K>, click: Listener) -> RepeatButton {
103        RepeatButton {
104            content: content.into_widget(),
105            click,
106            delay: REPEAT_BUTTON_DELAY,
107            interval: REPEAT_BUTTON_INTERVAL,
108            is_enabled: true,
109            is_tab_stop: true,
110            template: None,
111            key: None,
112        }
113    }
114
115    /// A text `Content`, as `<RepeatButton Content="…"/>`.
116    pub fn text(text: impl Into<String>, click: Listener) -> RepeatButton {
117        RepeatButton::new(Text::new(text), click)
118    }
119
120    /// XAML `Delay`.
121    pub fn delay(mut self, delay: Duration) -> RepeatButton {
122        self.delay = delay;
123        self
124    }
125
126    /// XAML `Interval`; `OnIntervalPropertyChanged` rejects a value that is not positive.
127    pub fn interval(mut self, interval: Duration) -> RepeatButton {
128        assert!(
129            !interval.is_zero(),
130            "RepeatButton.Interval must be positive"
131        );
132        self.interval = interval;
133        self
134    }
135
136    /// XAML `IsEnabled`.
137    pub fn is_enabled(mut self, enabled: bool) -> RepeatButton {
138        self.is_enabled = enabled;
139        self
140    }
141
142    /// XAML `IsTabStop`.
143    pub fn is_tab_stop(mut self, is_tab_stop: bool) -> Self {
144        self.is_tab_stop = is_tab_stop;
145        self
146    }
147
148    /// Replaces the visual template while preserving repeat, keyboard and pointer handling.
149    pub fn template(
150        mut self,
151        builder: impl Fn(&mut App, BuildContext, ControlStates, WidgetRef) -> WidgetRef + 'static,
152    ) -> Self {
153        self.template = Some(Rc::new(builder));
154        self
155    }
156
157    /// Sets this button's identity.
158    pub fn key(mut self, key: KeyRef) -> RepeatButton {
159        self.key = Some(key);
160        self
161    }
162}
163
164impl fmt::Debug for RepeatButton {
165    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166        f.debug_struct("RepeatButton")
167            .field("delay", &self.delay)
168            .field("interval", &self.interval)
169            .field("is_enabled", &self.is_enabled)
170            .finish_non_exhaustive()
171    }
172}
173
174impl StatefulWidget for RepeatButton {
175    type State = RepeatButtonState;
176    fn key(&self) -> Option<&KeyRef> {
177        self.key.as_ref()
178    }
179    fn create_state(&self) -> RepeatButtonState {
180        RepeatButtonState {
181            state: StateData::new(),
182            timer: None,
183            pointer_causing_repeat: false,
184            keyboard_causing_repeat: false,
185            pointer_over: false,
186            pressed: false,
187            key_down: false,
188            gamepad_a_key_down: false,
189            focused: false,
190            focus_node: None,
191        }
192    }
193}
194
195/// The repeat machinery of `RepeatButton_Partial.cpp`.
196pub struct RepeatButtonState {
197    state: StateData<RepeatButton>,
198    /// `m_tpTimer`, `Some` while the `TimelineTimer` is enabled.
199    timer: Option<Timer>,
200    /// `m_pointerCausingRepeat`.
201    pointer_causing_repeat: bool,
202    /// `m_keyboardCausingRepeat`.
203    keyboard_causing_repeat: bool,
204    /// `IsPointerOver` for the pressed pointer, from its position against the control's bounds.
205    pointer_over: bool,
206    pressed: bool,
207    key_down: bool,
208    gamepad_a_key_down: bool,
209    focused: bool,
210    focus_node: Option<FocusNodeRef>,
211}
212
213impl RepeatButtonState {
214    /// `RepeatButton::OnClick` → `ButtonBase::OnClick`: the `Click` event.
215    fn on_click(self: Handle<Self>, app: &mut App) {
216        self.widget(app).click.clone().call(app);
217    }
218
219    /// `RepeatButton::OnPointerPressed` over `ButtonBase::OnPointerPressed`: with the left button, the base raises `Click` (`ClickMode_Press`), then the pointer causes repeats.
220    fn on_pointer_pressed(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
221        if !self.widget(app).is_enabled || event.buttons != K_PRIMARY_BUTTON {
222            return;
223        }
224        self.set_state(app, |state| {
225            state.pointer_over = true;
226            state.pressed = true;
227        });
228        self.on_click(app);
229        app.get_mut(self).pointer_causing_repeat = true;
230        self.update_repeat_state(app);
231    }
232
233    /// `OnPointerEntered` / `OnPointerExited` for the active pointer: re-entering restarts the repeat (`UpdateRepeatState`); leaving lets the next tick stop it.
234    fn on_pointer_moved(self: Handle<Self>, app: &mut App, event: PointerMoveEvent) {
235        if !app.get(self).pointer_causing_repeat {
236            return;
237        }
238        let over = self.contains(app, event.local_position());
239        let was_over = std::mem::replace(&mut app.get_mut(self).pointer_over, over);
240        if over && !was_over {
241            self.update_repeat_state(app);
242        }
243    }
244
245    /// `RepeatButton::OnPointerReleased`, and the capture lost: the pointer stops causing repeats.
246    fn on_pointer_released(self: Handle<Self>, app: &mut App, kind: PointerDeviceKind) {
247        self.set_state(app, |state| {
248            state.pointer_causing_repeat = false;
249            if kind == PointerDeviceKind::Touch {
250                state.pointer_over = false;
251            }
252            if !state.key_down && !state.gamepad_a_key_down {
253                state.pressed = false;
254            }
255        });
256        self.update_repeat_state(app);
257    }
258
259    /// `RepeatButton::OnKeyDown` starts repetition for Space before `ButtonBase` processes the key.
260    fn on_key_event(self: Handle<Self>, app: &mut App, event: &KeyEvent) -> KeyEventResult {
261        if !self.widget(app).is_enabled {
262            return KeyEventResult::Ignored;
263        }
264        let key = event.logical_key();
265        if !is_press_key(key) {
266            if !matches!(event, KeyEvent::Up(_))
267                && (app.get(self).key_down || app.get(self).gamepad_a_key_down)
268            {
269                self.set_state(app, |state| {
270                    state.key_down = false;
271                    state.gamepad_a_key_down = false;
272                    state.pressed = false;
273                });
274            }
275            return KeyEventResult::Ignored;
276        }
277        match event {
278            KeyEvent::Down(_) | KeyEvent::Repeat(_) => {
279                if key == LogicalKeyboardKey::SPACE {
280                    app.get_mut(self).keyboard_causing_repeat = true;
281                    self.update_repeat_state(app);
282                }
283                if !app.get(self).pointer_causing_repeat
284                    && !app.get(self).key_down
285                    && !app.get(self).gamepad_a_key_down
286                {
287                    self.set_state(app, |state| {
288                        if key == LogicalKeyboardKey::GAME_BUTTON_A {
289                            state.gamepad_a_key_down = true;
290                        } else {
291                            state.key_down = true;
292                        }
293                        state.pressed = true;
294                    });
295                    self.on_click(app);
296                }
297            }
298            KeyEvent::Up(_) => {
299                self.set_state(app, |state| {
300                    if key == LogicalKeyboardKey::GAME_BUTTON_A {
301                        state.gamepad_a_key_down = false;
302                    } else {
303                        state.key_down = false;
304                    }
305                    if !state.pointer_causing_repeat {
306                        state.pressed = false;
307                    }
308                    if key == LogicalKeyboardKey::SPACE {
309                        state.keyboard_causing_repeat = false;
310                    }
311                });
312                self.update_repeat_state(app);
313            }
314        }
315        KeyEventResult::Handled
316    }
317
318    /// `RepeatButton::OnLostFocus` and `OnIsEnabledChanged`: neither input causes repeats any more.
319    fn reset_repeat(self: Handle<Self>, app: &mut App) {
320        self.set_state(app, |state| {
321            state.keyboard_causing_repeat = false;
322            state.pointer_causing_repeat = false;
323            state.key_down = false;
324            state.gamepad_a_key_down = false;
325            state.pressed = false;
326        });
327        self.update_repeat_state(app);
328    }
329
330    /// `RepeatButton::UpdateRepeatState`.
331    fn update_repeat_state(self: Handle<Self>, app: &mut App) {
332        if self.should_repeat(app) {
333            self.start_timer(app);
334        } else {
335            self.stop_timer(app);
336        }
337    }
338
339    /// `(m_pointerCausingRepeat && IsPointerOver) || m_keyboardCausingRepeat`, the condition of `UpdateRepeatState` and of `TickCallback`.
340    fn should_repeat(self: Handle<Self>, app: &App) -> bool {
341        let state = app.get(self);
342        (state.pointer_causing_repeat && state.pointer_over) || state.keyboard_causing_repeat
343    }
344
345    /// `RepeatButton::StartTimer`: a timer not already running starts at `Delay`.
346    fn start_timer(self: Handle<Self>, app: &mut App) {
347        if app.get(self).timer.is_some() {
348            return;
349        }
350        let delay = self.widget(app).delay;
351        self.schedule(app, delay);
352    }
353
354    /// `RepeatButton::StopTimer`.
355    fn stop_timer(self: Handle<Self>, app: &mut App) {
356        if let Some(timer) = app.get_mut(self).timer.take() {
357            timer.cancel(app);
358        }
359    }
360
361    /// `TimelineTimer::Start` with the interval it currently holds.
362    fn schedule(self: Handle<Self>, app: &mut App, duration: Duration) {
363        let timer = Timer::new(app, duration, Listener::new(move |app| self.tick(app)));
364        app.get_mut(self).timer = Some(timer);
365    }
366
367    /// `TimelineTimer::TimerCallback`: `RepeatButton::TickCallback` raises `Click` while the repeat condition holds and the timer restarts at `Interval`; otherwise it stops.
368    fn tick(self: Handle<Self>, app: &mut App) {
369        app.get_mut(self).timer = None;
370        if !app.get(self).pressed || !self.should_repeat(app) {
371            return;
372        }
373        self.on_click(app);
374        if !self.mounted(app) || !app.get(self).pressed || !self.should_repeat(app) {
375            return;
376        }
377        let interval = self.widget(app).interval;
378        self.schedule(app, interval);
379    }
380
381    /// `IsPointerOver`: whether `local` lies inside the control's bounds.
382    fn contains(self: Handle<Self>, app: &App, local: Offset) -> bool {
383        self.context(app)
384            .find_render_object(app)
385            .and_then(|object| object.as_box())
386            .is_some_and(|render_box| render_box.size(app).contains(local))
387    }
388}
389
390impl State for RepeatButtonState {
391    type Widget = RepeatButton;
392    waft_widgets::state_accessors!();
393
394    fn init_state(self: Handle<Self>, app: &mut App) {
395        crate::InputDevice::initialize(app);
396        let node: FocusNodeRef = FocusNode::new(app).into_erased();
397        node.set_skip_traversal(app, !self.widget(app).is_tab_stop);
398        node.set_on_key_event(
399            app,
400            Some(Rc::new(move |app, _, event| self.on_key_event(app, event))),
401        );
402        app.get_mut(self).focus_node = Some(node.clone());
403    }
404
405    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &RepeatButton) {
406        if self.widget(app).is_tab_stop != old_widget.is_tab_stop {
407            app.get(self)
408                .focus_node
409                .handle()
410                .expect("initialized focus node")
411                .set_skip_traversal(app, !self.widget(app).is_tab_stop);
412        }
413        // `RepeatButton::OnIsEnabledChanged`.
414        if self.widget(app).is_enabled != old_widget.is_enabled {
415            self.reset_repeat(app);
416        }
417    }
418
419    fn dispose(self: Handle<Self>, app: &mut App) {
420        self.stop_timer(app);
421        if let Some(node) = app.get_mut(self).focus_node.take() {
422            node.dispose(app);
423        }
424    }
425
426    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
427        let widget = self.widget(app).clone();
428        let state = app.get(self);
429        let states = ControlStates {
430            common: if !widget.is_enabled {
431                CommonState::Disabled
432            } else if state.pressed {
433                CommonState::Pressed
434            } else if state.pointer_over {
435                CommonState::PointerOver
436            } else {
437                CommonState::Normal
438            },
439            focused: state.focused && widget.is_enabled,
440        };
441        let presenter = if let Some(template) = widget.template {
442            template(app, context, states, widget.content)
443        } else {
444            template(app, context, widget.content, states)
445        };
446        let pointer = PointerListener::new()
447            .behavior(HitTestBehavior::Opaque)
448            .on_pointer_down(Rc::new(move |app, event| {
449                self.on_pointer_pressed(app, event)
450            }))
451            .on_pointer_move(Rc::new(move |app, event| self.on_pointer_moved(app, event)))
452            .on_pointer_up(Rc::new(move |app, event| {
453                self.on_pointer_released(app, event.kind)
454            }))
455            .on_pointer_cancel(Rc::new(move |app, event| {
456                self.on_pointer_released(app, event.kind);
457                self.set_state(app, |state| state.pressed = false);
458                self.stop_timer(app);
459            }))
460            .child(presenter);
461        FocusableActionDetector::new(pointer)
462            .enabled(widget.is_enabled)
463            .focus_node(
464                app.get(self)
465                    .focus_node
466                    .clone()
467                    .expect("initialized focus node"),
468            )
469            .on_show_hover_highlight(move |app, value| {
470                self.set_state(app, |state| state.pointer_over = value);
471                if value {
472                    self.update_repeat_state(app);
473                }
474            })
475            .on_focus_change(move |app, has_focus| {
476                let value = has_focus && crate::FocusState::current(app).shows_focus_visual();
477                self.set_state(app, |state| state.focused = value);
478                if !has_focus {
479                    self.reset_repeat(app);
480                }
481            })
482            .into_widget()
483    }
484}
485
486/// The `ControlTemplate` of `DefaultRepeatButtonStyle` for one set of states.
487fn template(
488    app: &mut App,
489    context: BuildContext,
490    content: WidgetRef,
491    states: ControlStates,
492) -> WidgetRef {
493    let resources = ThemeResources::of(app, context);
494    let brushes = repeat_button_brushes(&resources, states.common);
495    let presenter = repeat_button_presenter(
496        &resources,
497        brushes,
498        RepeatButtonSetters::default_style(&resources),
499        content,
500    );
501    FocusVisual::new(presenter, resources.theme)
502        .visible(states.focused)
503        .margin(REPEAT_BUTTON_FOCUS_VISUAL_MARGIN)
504        .corner_radius(resources.control_corner_radius[0])
505        .into_widget()
506}
507
508/// The values the template of `DefaultRepeatButtonStyle` takes from the style's setters, which
509/// a style based on it can change.
510#[derive(Clone, Copy, Debug, PartialEq)]
511pub(crate) struct RepeatButtonSetters {
512    /// `BorderThickness`: left, top, right, bottom.
513    pub(crate) border_thickness: [f64; 4],
514    /// `CornerRadius`.
515    pub(crate) corner_radius: f64,
516    /// `Padding`: left, top, right, bottom.
517    pub(crate) padding: [f64; 4],
518    /// `FontSize` of the content's text.
519    pub(crate) font_size: f64,
520}
521
522impl RepeatButtonSetters {
523    /// `DefaultRepeatButtonStyle`'s own, with the theme's values.
524    pub(crate) fn default_style(r: &ThemeResources) -> RepeatButtonSetters {
525        RepeatButtonSetters {
526            border_thickness: [r.button_border_theme_thickness[0]; 4],
527            corner_radius: r.control_corner_radius[0],
528            padding: r.button_padding,
529            font_size: r.control_content_theme_font_size,
530        }
531    }
532}
533
534/// `ContentPresenter`, the template of `DefaultRepeatButtonStyle`: `content` centered in a
535/// border drawn with `brushes` and `setters`, its background fading between states over 83 ms
536/// (`BrushTransition`).
537pub(crate) fn repeat_button_presenter(
538    r: &ThemeResources,
539    brushes: RepeatButtonBrushes,
540    setters: RepeatButtonSetters,
541    content: WidgetRef,
542) -> WidgetRef {
543    let text = control_text_style(r, setters.font_size, FontWeight::W400, brushes.foreground);
544    // `ContentPresenter`: `HorizontalContentAlignment` and `VerticalContentAlignment` are Center.
545    let label = Center::new()
546        .width_factor(1.0)
547        .height_factor(1.0)
548        .child(DefaultTextStyle::new(text, content))
549        .into_widget();
550    ColorTransition::new(
551        brushes.background,
552        r.control_faster_animation_duration,
553        move |_app, background| {
554            ControlBorder::new(Brush::Solid(background), brushes.border)
555                .border_thickness_ltrb(setters.border_thickness)
556                .corner_radius(setters.corner_radius)
557                .background_sizing(BackgroundSizing::InnerBorderEdge)
558                .padding(setters.padding)
559                .child(label.clone())
560                .into_widget()
561        },
562    )
563    .into_widget()
564}