Skip to main content

bhoo/systems/material/
helpers.rs

1use crate::*;
2
3impl Frame<'_> {
4    pub fn viewport(&self) -> Rect {
5        self.ui.viewport.unwrap_or(self.clip)
6    }
7    pub fn without_input(&mut self, blocked: bool, build: impl FnOnce(&mut Self)) {
8        let previous = self.input;
9        let previous_feedback = self.feedback_blocked;
10        self.feedback_blocked |= blocked;
11        if blocked {
12            self.input = Input {
13                time: previous.time,
14                ..Input::default()
15            };
16        }
17        build(self);
18        self.input = previous;
19        self.feedback_blocked = previous_feedback;
20    }
21    /// Block only pointer and wheel input (preserving keyboard focus and key events)
22    /// when a higher-z sibling or clickable descendant owns the pointer location.
23    pub fn without_pointer_input<R>(&mut self, blocked: bool, build: impl FnOnce(&mut Self) -> R) -> R {
24        let previous = self.input;
25        if blocked {
26            self.input.pointer = None;
27            self.input.pressed = false;
28            self.input.released = false;
29            self.input.scroll = [0.0, 0.0];
30        }
31        let result = build(self);
32        self.input = previous;
33        result
34    }
35    /// Cancel active child pointer capture when a parent gesture (e.g. scroll/drag) takes over:
36    /// clears `active` so releasing cannot trigger a click, while letting already-started
37    /// Material ripples fade out smoothly (`ACTION_CANCEL` semantics).
38    pub fn cancel_pointer_input<R>(&mut self, cancelled: bool, build: impl FnOnce(&mut Self) -> R) -> R {
39        let previous = self.input;
40        if cancelled {
41            self.ui.active = None;
42            self.input.cancelled = true;
43            self.input.pointer = None;
44            self.input.pressed = false;
45            self.input.released = false;
46            self.input.scroll = [0.0, 0.0];
47        }
48        let result = build(self);
49        self.input = previous;
50        result
51    }
52    pub(crate) fn any_scroll_dragging(&self) -> bool {
53        self.ui.scrolls.values().any(|s| s.dragging)
54    }
55    pub fn paint_rect(&mut self, bounds: Rect, radius: f32, color: Color) {
56        self.rect(bounds, radius, color);
57    }
58    /// Draw a caller-owned RGBA image with centered cover/contain geometry.
59    pub fn paint_image(&mut self, bounds: Rect, image: &Image, fit: ImageFit, radius: f32) -> bool {
60        self.paint_tinted_image(bounds, image, fit, radius, Color(255, 255, 255, 255))
61    }
62    /// Draw a caller-owned RGBA or MSDF image tinted by `color`.
63    pub fn paint_tinted_image(
64        &mut self,
65        bounds: Rect,
66        image: &Image,
67        fit: ImageFit,
68        radius: f32,
69        color: Color,
70    ) -> bool {
71        let Some((bounds, uv)) =
72            crate::media::fit_image(bounds, image.width(), image.height(), fit)
73        else {
74            return false;
75        };
76        if bounds.intersect(self.clip).width <= 0.0 || bounds.intersect(self.clip).height <= 0.0 {
77            return false;
78        }
79        self.commands.push(DrawCommand::Image {
80            bounds,
81            uv,
82            radius: radius.max(0.0),
83            color,
84            image: image.clone(),
85        });
86        true
87    }
88    /// Paint one of the bundled static Beer CSS shapes, contained within bounds.
89    pub fn paint_shape(&mut self, bounds: Rect, index: usize, color: Color) -> bool {
90        if index >= crate::beercss_shapes::SHAPES.len()
91            || bounds.width <= 0.0
92            || bounds.height <= 0.0
93        {
94            return false;
95        }
96        self.commands.push(DrawCommand::Shape {
97            bounds,
98            index: index as u8,
99            color,
100            rotation: 0.0,
101        });
102        true
103    }
104    /// Renderer-independent soft radial primitive. Stateful controls use `ink` internally.
105    pub fn paint_ink(
106        &mut self,
107        bounds: Rect,
108        corner_radius: f32,
109        center: [f32; 2],
110        radius: f32,
111        color: Color,
112    ) {
113        self.commands.push(DrawCommand::Ripple {
114            bounds,
115            corner_radius,
116            center,
117            radius,
118            color,
119            soft: true,
120        });
121    }
122    /// Beer CSS's centered hover wave: a 200ms expanding hard-edged state layer.
123    pub fn wave(&mut self, response: Response, radius: f32, color: Color) -> f32 {
124        use crate::timing::{Easing, TweenSpec};
125        let visible = response.enabled
126            && !response.pressed
127            && (response.hovered || response.focused && self.ui.keyboard_focus);
128        let target = f32::from(visible);
129        let progress = self.ui.motion.css_tween(
130            response.id,
131            87,
132            target,
133            0.0,
134            TweenSpec::new(0.2, Easing::Linear),
135            TweenSpec::new(0.0, Easing::Linear),
136        );
137        if visible {
138            let b = response.bounds;
139            let maximum = b.width.hypot(b.height) * 0.5;
140            self.commands.push(DrawCommand::Ripple {
141                bounds: b,
142                corner_radius: radius,
143                center: [b.x + b.width / 2.0, b.y + b.height / 2.0],
144                radius: maximum * (0.01 + 2.24 * progress),
145                color: color.opacity(0.1),
146                soft: false,
147            });
148        }
149        progress
150    }
151    pub fn paint_line(&mut self, from: [f32; 2], to: [f32; 2], width: f32, color: Color) {
152        self.commands.push(DrawCommand::Line {
153            from,
154            to,
155            width,
156            color,
157        });
158    }
159    /// Paint a circular arc with flat ends.
160    pub fn paint_arc(&mut self, bounds: Rect, start: f32, sweep: f32, stroke: f32, color: Color) {
161        self.commands.push(DrawCommand::Arc {
162            bounds,
163            start,
164            sweep,
165            stroke,
166            color,
167            rounded: false,
168        });
169    }
170    pub fn paint_text(&mut self, bounds: Rect, text: &str, color: Color) {
171        self.text_at(bounds, text, color);
172    }
173    pub fn action_at(&mut self, id: u64, bounds: Rect, label: &str, options: Options) -> Response {
174        self.button_at(id, bounds, label, options)
175    }
176    /// An interaction/semantic target for a composition with custom presentation.
177    pub fn target(
178        &mut self,
179        id: u64,
180        bounds: Rect,
181        label: &str,
182        enabled: bool,
183        role: Role,
184    ) -> Response {
185        let r = self.interact(id, bounds, enabled);
186        self.semantic(r, role, label, false, None, None, None);
187        r
188    }
189    pub fn target_roving(
190        &mut self,
191        id: u64,
192        bounds: Rect,
193        label: &str,
194        enabled: bool,
195        tab_stop: bool,
196    ) -> Response {
197        let r = self.target(id, bounds, label, enabled, Role::Button);
198        if !tab_stop && !r.focused && !r.clicked && self.ui.next_focus_order.last() == Some(&id) {
199            self.ui.next_focus_order.pop();
200        }
201        r
202    }
203    pub fn state_layer(&mut self, response: Response, radius: f32, color: Color) {
204        let hover = self.animate(response.id, 0, f32::from(response.hovered), 0.0);
205        let alpha = if response.focused && self.ui.keyboard_focus {
206            0.12
207        } else {
208            0.08 * hover
209        };
210        if response.enabled && alpha > 0.001 {
211            self.rect(response.bounds, radius, color.opacity(alpha));
212        }
213        self.ink(response, radius, color);
214    }
215    pub fn effect(&mut self, id: u64, property: u8, target: f32, initial: f32) -> f32 {
216        self.animate(id, property, target, initial)
217    }
218    /// Bounded geometry transition using AndroidX Standard spatial spring tokens.
219    pub fn spatial(&mut self, id: u64, property: u8, target: f32, initial: f32) -> f32 {
220        self.ui.motion.effect(
221            id,
222            property,
223            target,
224            initial,
225            self.ui.motion_scheme.spatial(),
226        )
227    }
228    /// Scroll offset supplied while building a nested-scroll bottom sheet.
229    pub fn bottom_sheet_scroll_offset(&self)->f32 {self.overlay_nested_scroll}
230    pub fn request_focus(&mut self, id: u64) {
231        if self.enabled {
232            self.ui.focused = Some(id);
233            self.ui.keyboard_focus = true;
234        }
235    }
236    pub fn focused_id(&self) -> Option<u64> {
237        self.ui.focused
238    }
239    /// Whether this response has a keyboard-visible focus state.
240    pub fn keyboard_focused(&self, response: Response) -> bool {
241        response.focused && self.ui.keyboard_focus
242    }
243    pub fn time(&self) -> f64 {
244        self.ui.time
245    }
246    pub fn reduced_motion(&self) -> bool {
247        self.ui.motion_preference == MotionPreference::Reduced
248    }
249    pub fn wake_at(&mut self, deadline: f64) {
250        if deadline.is_finite() && deadline > self.ui.time {
251            self.ui.wakeup = Some(self.ui.wakeup.map_or(deadline, |old| old.min(deadline)));
252        }
253    }
254    pub fn continuous(&mut self, bounds: Rect) -> bool {
255        let visible = bounds.intersect(self.clip);
256        if !self.reduced_motion() && visible.width > 0.0 && visible.height > 0.0 {
257            self.ui.continuous = true;
258            true
259        } else {
260            false
261        }
262    }
263    pub fn pressed_key(&self, key: Key) -> bool {
264        self.enabled && self.input.key.is_some_and(|k| k.key == key && k.pressed)
265    }
266    pub fn pointer_in(&self, bounds: Rect) -> bool {
267        self.input
268            .pointer
269            .is_some_and(|p| bounds.intersect(self.clip).contains(p))
270    }
271    pub fn scroll_y(&self, bounds: Rect) -> f32 {
272        if self.enabled
273            && self
274                .input
275                .pointer
276                .is_some_and(|p| bounds.intersect(self.clip).contains(p))
277        {
278            self.input.scroll[1]
279        } else {
280            0.0
281        }
282    }
283    pub fn compact_action_at(
284        &mut self,
285        id: u64,
286        bounds: Rect,
287        label: &str,
288        selected: bool,
289    ) -> Response {
290        let r = self.button_at(
291            id,
292            bounds,
293            "",
294            Options {
295                selected,
296                variant: ButtonVariant::Tonal,
297                ..Options::default()
298            },
299        );
300        let name = self.ui.text(label);
301        if let Some(node) = self.ui.semantics.last_mut() {
302            node.label = name;
303        }
304        self.text_at(
305            Rect {
306                x: bounds.x - 8.0,
307                width: bounds.width + 8.0,
308                ..bounds
309            },
310            label,
311            self.theme()
312                .text
313                .opacity(if r.enabled { 1.0 } else { 0.38 }),
314        );
315        r
316    }
317
318    /// Paint a rectangle with independent top and bottom corner radii without a center seam.
319    pub fn paint_asym_rect(&mut self, rect: Rect, top_radius: f32, bottom_radius: f32, color: Color) {
320        if rect.width <= 0.0 || rect.height <= 0.0 || color.3 == 0 {
321            return;
322        }
323        let max_r = (rect.width.min(rect.height) * 0.5).max(0.0);
324        let tr = top_radius.clamp(0.0, max_r);
325        let br = bottom_radius.clamp(0.0, max_r);
326        if (tr - br).abs() < 0.25 {
327            self.paint_rect(rect, tr, color);
328            return;
329        }
330        let mid_y = (rect.y + rect.height * 0.5).floor();
331        let top_h = (mid_y - rect.y).max(0.0);
332        let bot_h = (rect.y + rect.height - mid_y).max(0.0);
333        if top_h > 0.0 {
334            self.within(Rect { height: top_h, ..rect }, |f| {
335                f.paint_rect(
336                    Rect {
337                        height: rect.height.max(tr * 2.0),
338                        ..rect
339                    },
340                    tr,
341                    color,
342                );
343            });
344        }
345        if bot_h > 0.0 {
346            self.within(
347                Rect {
348                    y: mid_y,
349                    height: bot_h,
350                    ..rect
351                },
352                |f| {
353                    let h = rect.height.max(br * 2.0);
354                    f.paint_rect(
355                        Rect {
356                            y: rect.y + rect.height - h,
357                            height: h,
358                            ..rect
359                        },
360                        br,
361                        color,
362                    );
363                },
364            );
365        }
366    }
367
368    /// Paint an anti-aliased 4-corner inverse rounded mask over `bounds` using `outer_color`.
369    /// Useful for clipping rectangular content to rounded viewport/bezel corners.
370    pub fn paint_rounded_screen_mask(&mut self, bounds: Rect, corner_radius: f32, outer_color: Color) {
371        use std::sync::{Mutex, OnceLock};
372        let r_px = (corner_radius.round() as u32).clamp(8, 36);
373        let key = (r_px, [outer_color.0, outer_color.1, outer_color.2, outer_color.3]);
374        static MASK_CACHE: OnceLock<Mutex<HashMap<(u32, [u8; 4]), [Image; 4]>>> = OnceLock::new();
375        let lock = MASK_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
376        let corners: [Image; 4] = {
377            let mut map = lock.lock().expect("corner mask cache lock");
378            if let Some(existing) = map.get(&key) {
379                existing.clone()
380            } else {
381                if map.len() > 32 {
382                    map.clear();
383                }
384                let sz = r_px;
385                let rf = r_px as f32;
386                let make_corner = |cx: f32, cy: f32| -> Image {
387                    let mut rgba = vec![0u8; (sz * sz * 4) as usize];
388                    for y in 0..sz {
389                        for x in 0..sz {
390                            let dx = (x as f32 + 0.5) - cx;
391                            let dy = (y as f32 + 0.5) - cy;
392                            let dist = dx.hypot(dy);
393                            let cov = (dist - (rf - 0.5)).clamp(0.0, 1.0);
394                            let a = (cov * outer_color.3 as f32 + 0.5) as u8;
395                            let o = ((y * sz + x) * 4) as usize;
396                            rgba[o] = outer_color.0;
397                            rgba[o + 1] = outer_color.1;
398                            rgba[o + 2] = outer_color.2;
399                            rgba[o + 3] = a;
400                        }
401                    }
402                    Image::rgba(sz, sz, rgba).expect("valid corner mask")
403                };
404                let arr = [
405                    make_corner(rf, rf),
406                    make_corner(0.0, rf),
407                    make_corner(rf, 0.0),
408                    make_corner(0.0, 0.0),
409                ];
410                map.insert(key, arr.clone());
411                arr
412            }
413        };
414        let s = r_px as f32;
415        let rects = [
416            Rect { x: bounds.x, y: bounds.y, width: s, height: s },
417            Rect { x: bounds.x + bounds.width - s, y: bounds.y, width: s, height: s },
418            Rect { x: bounds.x, y: bounds.y + bounds.height - s, width: s, height: s },
419            Rect { x: bounds.x + bounds.width - s, y: bounds.y + bounds.height - s, width: s, height: s },
420        ];
421        for i in 0..4 {
422            self.paint_image(rects[i], &corners[i], ImageFit::Cover, 0.0);
423        }
424    }
425
426    /// Paint a Material 3 tonal surface with elevation tint (`background.mix(primary, 0.03 * level)`)
427    /// and drop shadow for `level > 0`.
428    pub fn surface(&mut self, bounds: Rect, radius: f32, level: u8) {
429        let t = self.theme();
430        if level > 0 {
431            self.elevation(bounds, radius, level);
432        }
433        let tint = (0.03 * f32::from(level.min(5))).clamp(0.0, 0.2);
434        self.paint_rect(bounds, radius, t.background.mix(t.primary, tint));
435    }
436
437    /// Lightweight arc-based rounded corner clip mask using `bg` without allocating textures.
438    /// Useful for clipping arbitrary sub-viewports (e.g. thumbnails or cards).
439    pub fn mask_rounded_corners(&mut self, rect: Rect, radius: f32, bg: Color) {
440        let r = radius.min(rect.width * 0.5).min(rect.height * 0.5);
441        if r <= 0.5 {
442            return;
443        }
444        let s = r * 0.48;
445        let outer = r + s;
446        let d = outer * 2.0;
447        let half_pi = std::f32::consts::FRAC_PI_2;
448        let pi = std::f32::consts::PI;
449        self.within(rect, |f| {
450            f.paint_arc(Rect { x: rect.x + r - outer, y: rect.y + r - outer, width: d, height: d }, pi, half_pi, s, bg);
451            f.paint_arc(Rect { x: rect.x + rect.width - r - outer, y: rect.y + r - outer, width: d, height: d }, -half_pi, half_pi, s, bg);
452            f.paint_arc(Rect { x: rect.x + rect.width - r - outer, y: rect.y + rect.height - r - outer, width: d, height: d }, 0.0, half_pi, s, bg);
453            f.paint_arc(Rect { x: rect.x + r - outer, y: rect.y + rect.height - r - outer, width: d, height: d }, half_pi, half_pi, s, bg);
454        });
455    }
456}
457
458#[cfg(test)]
459#[path = "helpers.spec.rs"]
460mod tests;