Skip to main content

waft_winui/primitives/
control_border.rs

1//! The background, border and corner radius every template's root `ContentPresenter`, `Border` or `Grid` carries: XAML `Background`, `BorderBrush`, `BorderThickness`, `CornerRadius`, `BackgroundSizing` and `Padding`.
2
3use crate::Brush;
4use waft_embedder::{Canvas, Clip, Offset, RRect, Radius, Size, TextBaseline};
5use waft_foundation::App;
6use waft_painting::{BorderRadius, ClipContext, EdgeInsets, EdgeInsetsGeometry};
7use waft_rendering::*;
8use waft_widgets::*;
9
10/// XAML `BackgroundSizing`: whether the background stops at the border's inner edge or extends under it.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub enum BackgroundSizing {
13    /// Paints the background inside the border's inner edge.
14    #[default]
15    InnerBorderEdge,
16    /// Paints the background beneath the border up to its outer edge.
17    OuterBorderEdge,
18}
19
20/// A rounded rectangle with a background brush and a border brush, the child inside the border and padding.
21#[derive(Clone, Debug)]
22pub struct ControlBorder {
23    /// The content placed inside the border and padding.
24    pub child: Option<WidgetRef>,
25    /// The brush filling the area selected by `background_sizing`.
26    pub background: Option<Brush>,
27    /// The brush filling the ring between the inner and outer border outlines.
28    pub border_brush: Option<Brush>,
29    /// Left, top, right, bottom.
30    pub border_thickness: [f64; 4],
31    /// Top-left, top-right, bottom-right, bottom-left.
32    pub corner_radius: [f64; 4],
33    /// Whether the background extends beneath the border.
34    pub background_sizing: BackgroundSizing,
35    /// Left, top, right, bottom, inside the border.
36    pub padding: [f64; 4],
37}
38
39impl ControlBorder {
40    /// Creates border chrome with the supplied brushes and a one-pixel border.
41    pub fn new(background: Brush, border_brush: Brush) -> ControlBorder {
42        Self::new_optional(Some(background), Some(border_brush))
43    }
44
45    /// Preserves XAML's distinction between an absent brush and a transparent brush.
46    pub fn new_optional(background: Option<Brush>, border_brush: Option<Brush>) -> Self {
47        ControlBorder {
48            child: None,
49            background,
50            border_brush,
51            border_thickness: [1.0; 4],
52            corner_radius: [0.0; 4],
53            background_sizing: BackgroundSizing::InnerBorderEdge,
54            padding: [0.0; 4],
55        }
56    }
57
58    /// Sets the content inside the border and padding.
59    #[cfg_attr(debug_assertions, track_caller)]
60    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> ControlBorder {
61        self.child = Some(child.into_widget());
62        self
63    }
64
65    /// Sets a uniform border width on all four sides.
66    pub fn border_thickness(mut self, thickness: f64) -> ControlBorder {
67        self.border_thickness = [thickness; 4];
68        self
69    }
70
71    /// XAML `BorderThickness`, in left, top, right, bottom order.
72    pub fn border_thickness_ltrb(mut self, thickness: [f64; 4]) -> ControlBorder {
73        self.border_thickness = thickness;
74        self
75    }
76
77    /// Sets a uniform radius on all four corners.
78    pub fn corner_radius(mut self, radius: f64) -> ControlBorder {
79        self.corner_radius = [radius; 4];
80        self
81    }
82
83    /// XAML `CornerRadius`, in top-left, top-right, bottom-right, bottom-left order.
84    pub fn corner_radius_corners(mut self, radii: [f64; 4]) -> ControlBorder {
85        self.corner_radius = radii;
86        self
87    }
88
89    /// Sets whether the background fills beneath the border.
90    pub fn background_sizing(mut self, sizing: BackgroundSizing) -> ControlBorder {
91        self.background_sizing = sizing;
92        self
93    }
94
95    /// Sets additional insets inside the border in left, top, right, bottom order.
96    pub fn padding(mut self, padding: [f64; 4]) -> ControlBorder {
97        self.padding = padding;
98        self
99    }
100}
101
102impl StatelessWidget for ControlBorder {
103    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
104        let [left, top, right, bottom] = self.padding;
105        let thickness = self.border_thickness;
106        let style = ControlBorderStyle {
107            background: self.background,
108            border_brush: self.border_brush,
109            border_thickness: thickness,
110            corner_radius: self.corner_radius,
111            background_sizing: self.background_sizing,
112        };
113        let inner = Padding::new(EdgeInsetsGeometry::from_ltrb(
114            left + thickness[0],
115            top + thickness[1],
116            right + thickness[2],
117            bottom + thickness[3],
118        ));
119        let inner = match &self.child {
120            Some(child) => inner.child(child.clone()),
121            None => inner,
122        };
123        let [top_left, top_right, bottom_right, bottom_left] =
124            self.corner_radius.map(Radius::circular);
125        let rounded = self.corner_radius.iter().any(|radius| *radius > 0.0);
126        ClipRRect::new()
127            .border_radius(
128                BorderRadius::only(top_left, top_right, bottom_left, bottom_right).into(),
129            )
130            .clip_behavior(if rounded { Clip::AntiAlias } else { Clip::None })
131            .child(BorderPaint {
132                style,
133                child: inner.into_widget(),
134            })
135            .into_widget()
136    }
137}
138
139/// Source brushes and geometry used for both painting and hit testing.
140#[derive(Clone, Copy, Debug, PartialEq)]
141struct ControlBorderStyle {
142    /// An absent background leaves the interior out of this element's hit area.
143    background: Option<Brush>,
144
145    /// An absent border leaves the stroke out of this element's hit area.
146    border_brush: Option<Brush>,
147
148    /// Width of the four border edges.
149    border_thickness: [f64; 4],
150
151    /// Physical corner radii in clockwise order.
152    corner_radius: [f64; 4],
153
154    /// Chooses whether the fill extends under the border.
155    background_sizing: BackgroundSizing,
156}
157
158impl ControlBorderStyle {
159    /// Uses the same rounded outlines for drawing and pointer hit testing.
160    fn outlines(self, size: Size) -> (RRect, RRect) {
161        let bounds = Offset::ZERO & size;
162        let [top_left, top_right, bottom_right, bottom_left] =
163            self.corner_radius.map(Radius::circular);
164        let outer =
165            RRect::from_rect_and_corners(bounds, top_left, top_right, bottom_right, bottom_left)
166                .scale_radii();
167        let [left, top, right, bottom] = self.border_thickness;
168        let inner = EdgeInsets::from_ltrb(left, top, right, bottom).deflate_rrect(outer);
169        (outer, inner)
170    }
171
172    /// CBorder::HitTestLocalInternalImpl for the brush shapes supported by this kit.
173    fn hit_test(self, size: Size, point: Offset) -> bool {
174        if size.width() <= 0.0 || size.height() <= 0.0 {
175            return false;
176        }
177        let (outer, inner) = self.outlines(size);
178        let in_outer = outer.contains(point);
179        let in_inner = inner.contains(point);
180        let background_hit = self.background.is_some()
181            && match self.background_sizing {
182                BackgroundSizing::InnerBorderEdge => in_inner,
183                BackgroundSizing::OuterBorderEdge => in_outer,
184            };
185        background_hit || (self.border_brush.is_some() && in_outer && !in_inner)
186    }
187
188    /// Paints the fill followed by the stroke, before the child.
189    fn paint(self, canvas: &mut Canvas, size: Size) {
190        let bounds = Offset::ZERO & size;
191        let (outer, inner) = self.outlines(size);
192        let background_rect = match self.background_sizing {
193            BackgroundSizing::InnerBorderEdge => inner,
194            BackgroundSizing::OuterBorderEdge => outer,
195        };
196        if let Some(background) = self.background
197            && (matches!(background, Brush::Acrylic(_))
198                || background.representative_color().a > 0.0)
199        {
200            background.paint_rrect(canvas, background_rect, bounds);
201        }
202        if let Some(border) = self.border_brush
203            && self
204                .border_thickness
205                .iter()
206                .any(|thickness| *thickness > 0.0)
207            && (matches!(border, Brush::Acrylic(_)) || border.representative_color().a > 0.0)
208        {
209            border.paint_drrect(canvas, outer, inner, bounds);
210        }
211    }
212}
213
214/// A render-object widget keeps hit testing tied to layout size rather than the last paint.
215#[derive(Debug)]
216struct BorderPaint {
217    /// Current source geometry and brushes.
218    style: ControlBorderStyle,
219
220    /// Child with border thickness and padding already applied.
221    child: WidgetRef,
222}
223
224impl RenderObjectWidget for BorderPaint {
225    type RenderObject = RenderBorderPaint;
226
227    fn create_render_object(&self, app: &mut App, _: BuildContext) -> AnyRenderObject {
228        RenderHandle::new_box(
229            app,
230            RenderBorderPaint {
231                render_object: RenderObjectData::new(),
232                render_box: RenderBoxData::new(),
233                child: RenderObjectWithChildData::new(),
234                style: self.style,
235            },
236        )
237        .as_object()
238    }
239
240    fn update_render_object(
241        &self,
242        app: &mut App,
243        _: BuildContext,
244        render: RenderHandle<RenderBorderPaint>,
245    ) {
246        if render.get(app).style != self.style {
247            render.get_mut(app).style = self.style;
248            render.as_object().mark_needs_paint(app);
249        }
250    }
251}
252
253impl SingleChildRenderObjectWidget for BorderPaint {
254    fn child(&self) -> Option<&WidgetRef> {
255        Some(&self.child)
256    }
257}
258
259/// Native layout proxy with WinUI's optional-brush hit-test rules.
260struct RenderBorderPaint {
261    /// Render identity and invalidation.
262    render_object: RenderObjectData,
263
264    /// Layout geometry used before any paint has occurred.
265    render_box: RenderBoxData,
266
267    /// The padded child.
268    child: RenderObjectWithChildData<AnyRenderBox>,
269
270    /// Source appearance and hit area.
271    style: ControlBorderStyle,
272}
273
274impl RenderObjectWithChildMixin for RenderBorderPaint {
275    type ChildType = AnyRenderBox;
276
277    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
278        &self.get(app).child
279    }
280
281    fn child_data_mut(
282        self: RenderHandle<Self>,
283        app: &mut App,
284    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
285        &mut self.get_mut(app).child
286    }
287}
288
289impl RenderProxyBoxMixin for RenderBorderPaint {}
290
291impl RenderObject for RenderBorderPaint {
292    waft_rendering::render_object_accessors!();
293
294    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
295        RenderProxyBoxMixin::perform_layout(self, app);
296    }
297
298    fn visit_children(
299        self: RenderHandle<Self>,
300        app: &App,
301        visitor: &mut dyn FnMut(AnyRenderObject),
302    ) {
303        if let Some(child) = self.child(app) {
304            visitor(child.as_object());
305        }
306    }
307
308    fn paint(
309        self: RenderHandle<Self>,
310        app: &mut App,
311        context: &mut PaintingContext,
312        offset: Offset,
313    ) {
314        let style = self.get(app).style;
315        let size = self.size(app);
316        let canvas = context.canvas();
317        canvas.save();
318        canvas.translate(offset.dx() as f32, offset.dy() as f32);
319        style.paint(canvas, size);
320        canvas.restore();
321        RenderProxyBoxMixin::paint(self, app, context, offset);
322    }
323}
324
325impl RenderBox for RenderBorderPaint {
326    waft_rendering::render_box_accessors!();
327
328    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
329        RenderProxyBoxMixin::compute_min_intrinsic_width(self, app, height)
330    }
331
332    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
333        RenderProxyBoxMixin::compute_max_intrinsic_width(self, app, height)
334    }
335
336    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
337        RenderProxyBoxMixin::compute_min_intrinsic_height(self, app, width)
338    }
339
340    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
341        RenderProxyBoxMixin::compute_max_intrinsic_height(self, app, width)
342    }
343
344    fn compute_dry_layout(
345        self: RenderHandle<Self>,
346        app: &mut App,
347        constraints: BoxConstraints,
348    ) -> Size {
349        RenderProxyBoxMixin::compute_dry_layout(self, app, constraints)
350    }
351
352    fn compute_distance_to_actual_baseline(
353        self: RenderHandle<Self>,
354        app: &mut App,
355        baseline: TextBaseline,
356    ) -> Option<f64> {
357        RenderProxyBoxMixin::compute_distance_to_actual_baseline(self, app, baseline)
358    }
359
360    fn compute_dry_baseline(
361        self: RenderHandle<Self>,
362        app: &mut App,
363        constraints: BoxConstraints,
364        baseline: TextBaseline,
365    ) -> Option<f64> {
366        RenderProxyBoxMixin::compute_dry_baseline(self, app, constraints, baseline)
367    }
368
369    fn hit_test_self(self: RenderHandle<Self>, app: &App, position: Offset) -> bool {
370        self.get(app).style.hit_test(self.size(app), position)
371    }
372
373    fn hit_test_children(
374        self: RenderHandle<Self>,
375        app: &mut App,
376        result: &mut BoxHitTestResult<'_>,
377        position: Offset,
378    ) -> bool {
379        // UIElement::HitTestRoundedCornerClip also clips descendants to the outer outline.
380        let outer = self.get(app).style.outlines(self.size(app)).0;
381        outer.contains(position)
382            && RenderProxyBoxMixin::hit_test_children(self, app, result, position)
383    }
384}
385
386#[cfg(test)]
387mod tests {
388    use waft_embedder::{Color, TextDirection};
389    use waft_widgets::testing::WidgetTester;
390    use waft_widgets::{
391        CustomScrollView, Directionality, GlobalKey, IntoWidget, LayoutBuilder, SizedBox,
392        SliverList, SliverToBoxAdapter,
393    };
394
395    use super::*;
396    use crate::Margin;
397
398    /// Every widget names the line of the app's code that made it: a child passed to a setter,
399    /// a child passed to a constructor, a sliver list built from its builder, and a widget that
400    /// is its own tree node.
401    #[test]
402    fn each_widget_names_the_line_that_made_it() {
403        let mut tester = WidgetTester::new();
404        let setter_key = GlobalKey::new();
405        let constructor_key = GlobalKey::new();
406        let builder_key = GlobalKey::new();
407        let tree_node_key = GlobalKey::new();
408
409        let border = ControlBorder::new(
410            Brush::Solid(Color::new(0xFF000000)),
411            Brush::Solid(Color::new(0xFFFFFFFF)),
412        );
413        let setter_line = line!() + 1;
414        let setter = border.child(SizedBox::new().key(setter_key.clone().into()));
415        let setter = setter.into_widget();
416
417        let constructor_child = SizedBox::new().key(constructor_key.clone().into());
418        let constructor_line = line!() + 1;
419        let constructor = Margin::new([1.0; 4], constructor_child).into_widget();
420
421        let builder = SliverList::builder(|_app, _context, index| {
422            (index < 1).then(|| SizedBox::new().height(10.0).into_widget())
423        })
424        .item_count(1)
425        .key(builder_key.clone().into());
426        let builder_line = line!() + 1;
427        let builder = builder.into_widget();
428
429        let tree_node =
430            LayoutBuilder::new(|_app, _context, _constraints| SizedBox::new().into_widget())
431                .key(tree_node_key.clone().into());
432        let tree_node_line = line!() + 1;
433        let tree_node = tree_node.into_widget();
434
435        tester.pump_widget(Directionality::new(
436            TextDirection::Ltr,
437            CustomScrollView::new().slivers([
438                SliverToBoxAdapter::new().child(setter).into_widget(),
439                SliverToBoxAdapter::new().child(constructor).into_widget(),
440                builder,
441                SliverToBoxAdapter::new().child(tree_node).into_widget(),
442            ]),
443        ));
444
445        for (key, line) in [
446            (setter_key, setter_line),
447            (constructor_key, constructor_line),
448            (builder_key, builder_line),
449            (tree_node_key, tree_node_line),
450        ] {
451            let app = tester.cell.borrow();
452            let context = key
453                .current_context(&app)
454                .expect("the widget is in the tree");
455            let location = context
456                .widget(&app)
457                .creation_location()
458                .expect("a creation location");
459            assert_eq!(location.file(), file!());
460            assert_eq!(location.line(), line);
461        }
462    }
463}