Skip to main content

waft_winui/primitives/
focus_visual.rs

1//! XAML's system focus visual (`UseSystemFocusVisuals="True"`): a two-pixel primary ring outside the control with a one-pixel secondary ring inside it, offset by the control's `FocusVisualMargin`, shown when the control requests a focus highlight.
2
3use crate::{Brush, Theme};
4use waft_embedder::{Canvas, Color, Offset, RRect, Radius, Size};
5use waft_foundation::App;
6use waft_rendering::CustomPainter;
7use waft_widgets::*;
8
9/// XAML `SystemFocusVisualPrimaryThickness`.
10pub const FOCUS_VISUAL_PRIMARY_THICKNESS: f64 = 2.0;
11/// XAML `SystemFocusVisualSecondaryThickness`.
12pub const FOCUS_VISUAL_SECONDARY_THICKNESS: f64 = 1.0;
13
14/// Draws the focus rings around `child` when `visible`, `margin` (left, top, right, bottom; negative grows outward, as XAML's `FocusVisualMargin`) away from its bounds.
15#[derive(Clone, Debug)]
16pub struct FocusVisual {
17    pub child: WidgetRef,
18    pub visible: bool,
19    pub margin: [f64; 4],
20    pub corner_radius: f64,
21    pub theme: Theme,
22    /// XAML `FocusVisualPrimaryBrush`; `None` is `SystemControlFocusVisualPrimaryBrush`.
23    pub primary_brush: Option<Color>,
24    /// XAML `FocusVisualSecondaryBrush`; `None` is `SystemControlFocusVisualSecondaryBrush`.
25    pub secondary_brush: Option<Color>,
26}
27
28impl FocusVisual {
29    #[cfg_attr(debug_assertions, track_caller)]
30    pub fn new<K>(child: impl IntoWidget<K>, theme: Theme) -> FocusVisual {
31        FocusVisual {
32            child: child.into_widget(),
33            visible: false,
34            margin: [0.0; 4],
35            corner_radius: 0.0,
36            theme,
37            primary_brush: None,
38            secondary_brush: None,
39        }
40    }
41
42    pub fn visible(mut self, visible: bool) -> FocusVisual {
43        self.visible = visible;
44        self
45    }
46
47    /// XAML `FocusVisualMargin`.
48    pub fn margin(mut self, margin: [f64; 4]) -> FocusVisual {
49        self.margin = margin;
50        self
51    }
52
53    pub fn corner_radius(mut self, radius: f64) -> FocusVisual {
54        self.corner_radius = radius;
55        self
56    }
57
58    /// XAML `FocusVisualPrimaryBrush`.
59    pub fn primary_brush(mut self, color: Color) -> FocusVisual {
60        self.primary_brush = Some(color);
61        self
62    }
63
64    /// XAML `FocusVisualSecondaryBrush`.
65    pub fn secondary_brush(mut self, color: Color) -> FocusVisual {
66        self.secondary_brush = Some(color);
67        self
68    }
69
70    /// `SystemControlFocusVisualPrimaryBrush`: the system's base-high colour, black in light and white in dark.
71    pub fn primary_color(theme: Theme) -> Color {
72        match theme {
73            Theme::Light => Color::from_argb(255, 0, 0, 0),
74            Theme::Dark => Color::from_argb(255, 255, 255, 255),
75        }
76    }
77
78    /// `SystemControlFocusVisualSecondaryBrush`: the system's alt-medium colour, white at 60 % in light and black at 60 % in dark.
79    pub fn secondary_color(theme: Theme) -> Color {
80        match theme {
81            Theme::Light => Color::from_argb(153, 255, 255, 255),
82            Theme::Dark => Color::from_argb(153, 0, 0, 0),
83        }
84    }
85}
86
87impl StatelessWidget for FocusVisual {
88    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
89        // The tree keeps the same shape whether the ring shows or not, so the child's elements
90        // (and a pointer's cached hit-test path through them) survive focus arriving mid-press.
91        let [left, top, right, bottom] = self.margin;
92        let ring = FocusRingPainter {
93            visible: self.visible,
94            primary: Brush::Solid(
95                self.primary_brush
96                    .unwrap_or_else(|| FocusVisual::primary_color(self.theme)),
97            ),
98            secondary: Brush::Solid(
99                self.secondary_brush
100                    .unwrap_or_else(|| FocusVisual::secondary_color(self.theme)),
101            ),
102            corner_radius: self.corner_radius - left.min(0.0),
103        };
104        // Passthrough: the child sees the constraints it would see without the ring.
105        Stack::new()
106            .fit(waft_rendering::StackFit::Passthrough)
107            .clip_behavior(waft_embedder::Clip::None)
108            .children(vec![
109                self.child.clone(),
110                Positioned::new(CustomPaint::new().painter(ring))
111                    .left(left)
112                    .top(top)
113                    .right(right)
114                    .bottom(bottom)
115                    .into_widget(),
116            ])
117            .into_widget()
118    }
119}
120
121#[derive(Clone, Debug, PartialEq)]
122struct FocusRingPainter {
123    visible: bool,
124    primary: Brush,
125    secondary: Brush,
126    corner_radius: f64,
127}
128
129impl CustomPainter for FocusRingPainter {
130    fn paint(&self, _app: &mut App, canvas: &mut Canvas, size: Size) {
131        if !self.visible {
132            return;
133        }
134        let bounds = Offset::ZERO & size;
135        let outer = RRect::from_rect_and_radius(bounds, Radius::circular(self.corner_radius));
136        self.primary.paint_rrect_stroke(
137            canvas,
138            outer.deflate(FOCUS_VISUAL_PRIMARY_THICKNESS / 2.0),
139            bounds,
140            FOCUS_VISUAL_PRIMARY_THICKNESS,
141        );
142        self.secondary.paint_rrect_stroke(
143            canvas,
144            outer.deflate(FOCUS_VISUAL_PRIMARY_THICKNESS + FOCUS_VISUAL_SECONDARY_THICKNESS / 2.0),
145            bounds,
146            FOCUS_VISUAL_SECONDARY_THICKNESS,
147        );
148    }
149
150    /// The ring is drawn over the control but never in front of it for the pointer.
151    fn hit_test(&self, _app: &App, _position: Offset) -> Option<bool> {
152        Some(false)
153    }
154
155    fn should_repaint(&self, _app: &App, old_delegate: &dyn CustomPainter) -> bool {
156        old_delegate.as_any().downcast_ref::<Self>() != Some(self)
157    }
158
159    fn as_any(&self) -> &dyn std::any::Any {
160        self
161    }
162}