Skip to main content

cranpose_ui/modifier/
graphics_layer.rs

1use std::rc::Rc;
2
3use cranpose_ui_graphics::{
4    BlendMode, Color, ColorFilter, CompositingStrategy, Density, Dp, GradientBlurDirection,
5    GradientCutMaskSpec, GradientFadeMaskSpec, LayerShape, Px, RenderEffect, RoundedCornerShape,
6    RuntimeShader, TransformOrigin, gradient_blur_effect, gradient_cut_mask_effect,
7    gradient_fade_dst_out_effect, rounded_alpha_mask_effect,
8};
9
10use super::{GraphicsLayer, Modifier, inspector_metadata};
11use crate::modifier_nodes::{GraphicsLayerElement, LazyGraphicsLayerElement};
12
13fn backdrop_blur_layer(radius: Dp, shape: LayerShape) -> GraphicsLayer {
14    let density = Density::from_scale(crate::render_state::current_density());
15    let radius_px = radius.to_px(density).max(Px::ZERO);
16    GraphicsLayer {
17        backdrop_effect: (radius_px.0 > 0.0).then(|| RenderEffect::blur(radius_px.0)),
18        shape,
19        clip: true,
20        ..Default::default()
21    }
22}
23
24fn backdrop_gradient_blur_layer(
25    start_radius: Dp,
26    end_radius: Dp,
27    direction: GradientBlurDirection,
28) -> GraphicsLayer {
29    let density = Density::from_scale(crate::render_state::current_density());
30    let start_px = start_radius.to_px(density).max(Px::ZERO);
31    let end_px = end_radius.to_px(density).max(Px::ZERO);
32    GraphicsLayer {
33        backdrop_effect: (start_px.0 > 0.0 || end_px.0 > 0.0)
34            .then(|| gradient_blur_effect(start_px.0, end_px.0, direction)),
35        shape: LayerShape::Rectangle,
36        clip: true,
37        ..Default::default()
38    }
39}
40
41impl Modifier {
42    /// Apply a lazily evaluated graphics layer.
43    ///
44    /// The closure is evaluated during scene building, not composition, which lets
45    /// layer properties update without forcing recomposition.
46    ///
47    /// Example:
48    /// `Modifier::empty().graphics_layer(|| GraphicsLayer { alpha: 0.5, ..Default::default() })`
49    ///
50    /// # A drag that drives the translation must not be read inside it
51    ///
52    /// [`PointerEvent::position`](crate::modifier::PointerEvent::position) is
53    /// in the receiving node's own space, so a node this layer translates
54    /// reports a finger that has moved only as far as it OUTRAN the
55    /// translation. Feed that position back into `translation_x` and the
56    /// gesture measures itself:
57    ///
58    /// ```text
59    /// reported = finger - offset          offset = reported - start
60    ///         => offset = (finger - start) / 2
61    /// ```
62    ///
63    /// The offset converges on half the finger's travel and can never exceed
64    /// it, so a swipe-to-dismiss whose threshold is half the width never
65    /// crosses it however far the finger goes -- silently, with the content
66    /// sliding convincingly the whole time.
67    ///
68    /// Two ways out, and [`SwipeToDismiss`](crate::widgets::SwipeToDismiss)
69    /// uses both:
70    ///
71    /// - put `pointer_input` on a node OUTSIDE the translated one, which is
72    ///   also how Compose's own `SwipeToDismissBox` is built -- the drag is
73    ///   detected on the box, the content carries the layer;
74    /// - or read
75    ///   [`PointerEvent::global_position`](crate::modifier::PointerEvent::global_position),
76    ///   which no layer transform touches.
77    pub fn graphics_layer(self, layer: impl Fn() -> GraphicsLayer + 'static) -> Self {
78        let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(layer)))
79            .with_inspector_metadata(inspector_metadata("graphicsLayer", |info| {
80                info.add_property("lazy", "true");
81            }));
82        self.then(modifier)
83    }
84
85    /// Apply a concrete graphics layer snapshot.
86    ///
87    /// This is useful for parameter-style wrappers that already build a fixed
88    /// [`GraphicsLayer`] value.
89    pub fn graphics_layer_value(self, layer: GraphicsLayer) -> Self {
90        let inspector_values = layer.clone();
91        let modifier = Self::with_element(GraphicsLayerElement::new(layer))
92            .with_inspector_metadata(inspector_metadata("graphicsLayer", move |info| {
93                info.add_property("alpha", inspector_values.alpha.to_string());
94                info.add_property("scale", inspector_values.scale.to_string());
95                info.add_property("scaleX", inspector_values.scale_x.to_string());
96                info.add_property("scaleY", inspector_values.scale_y.to_string());
97                info.add_property("rotationX", inspector_values.rotation_x.to_string());
98                info.add_property("rotationY", inspector_values.rotation_y.to_string());
99                info.add_property("rotationZ", inspector_values.rotation_z.to_string());
100                info.add_property(
101                    "cameraDistance",
102                    inspector_values.camera_distance.to_string(),
103                );
104                info.add_property(
105                    "transformOrigin",
106                    format!(
107                        "{},{}",
108                        inspector_values.transform_origin.pivot_fraction_x,
109                        inspector_values.transform_origin.pivot_fraction_y
110                    ),
111                );
112                info.add_property("translationX", inspector_values.translation_x.to_string());
113                info.add_property("translationY", inspector_values.translation_y.to_string());
114                info.add_property(
115                    "shadowElevation",
116                    inspector_values.shadow_elevation.to_string(),
117                );
118                info.add_property("shape", format!("{:?}", inspector_values.shape));
119                info.add_property("clip", inspector_values.clip.to_string());
120                info.add_property(
121                    "ambientShadowColor",
122                    format!("{:?}", inspector_values.ambient_shadow_color),
123                );
124                info.add_property(
125                    "spotShadowColor",
126                    format!("{:?}", inspector_values.spot_shadow_color),
127                );
128                info.add_property(
129                    "compositingStrategy",
130                    format!("{:?}", inspector_values.compositing_strategy),
131                );
132                info.add_property("blendMode", format!("{:?}", inspector_values.blend_mode));
133                if let Some(filter) = inspector_values.color_filter {
134                    info.add_property("colorFilter", format!("{filter:?}"));
135                }
136            }));
137        self.then(modifier)
138    }
139
140    /// Compose-compatible parameter-style graphics layer entry point.
141    ///
142    /// This mirrors `Modifier.graphicsLayer(...)` style APIs and maps directly to
143    /// [`GraphicsLayer`] fields currently implemented by the renderer stack.
144    #[allow(clippy::too_many_arguments)]
145    pub fn graphics_layer_params(
146        self,
147        scale_x: f32,
148        scale_y: f32,
149        alpha: f32,
150        translation_x: f32,
151        translation_y: f32,
152        shadow_elevation: f32,
153        rotation_x: f32,
154        rotation_y: f32,
155        rotation_z: f32,
156        camera_distance: f32,
157        transform_origin: TransformOrigin,
158        shape: LayerShape,
159        clip: bool,
160        render_effect: Option<RenderEffect>,
161        ambient_shadow_color: Color,
162        spot_shadow_color: Color,
163        compositing_strategy: CompositingStrategy,
164        blend_mode: BlendMode,
165        color_filter: Option<ColorFilter>,
166    ) -> Self {
167        self.graphics_layer_value(GraphicsLayer {
168            alpha,
169            scale: 1.0,
170            scale_x,
171            scale_y,
172            rotation_x,
173            rotation_y,
174            rotation_z,
175            camera_distance,
176            transform_origin,
177            translation_x,
178            translation_y,
179            shadow_elevation,
180            ambient_shadow_color,
181            spot_shadow_color,
182            shape,
183            clip,
184            compositing_strategy,
185            blend_mode,
186            color_filter,
187            render_effect,
188            backdrop_effect: None,
189        })
190    }
191
192    /// Compose-compatible block-style graphics layer entry point.
193    ///
194    /// Example:
195    /// `Modifier::empty().graphics_layer_block(|layer| { layer.alpha = 0.5; layer.scale_x = 1.2; })`
196    pub fn graphics_layer_block(self, configure: impl Fn(&mut GraphicsLayer) + 'static) -> Self {
197        self.graphics_layer(move || {
198            let mut layer = GraphicsLayer::default();
199            configure(&mut layer);
200            layer
201        })
202    }
203
204    /// Compose-style elevation shadow convenience.
205    ///
206    /// This mirrors `Modifier.shadow(elevation)` defaults:
207    /// rectangle shape, black ambient/spot colors, and clipping enabled when
208    /// elevation is positive.
209    pub fn shadow(self, elevation: f32) -> Self {
210        self.shadow_with(
211            elevation,
212            LayerShape::Rectangle,
213            elevation > 0.0,
214            Color::BLACK,
215            Color::BLACK,
216        )
217    }
218
219    /// Compose-style shadow API with explicit shape/clip/colors.
220    pub fn shadow_with(
221        self,
222        elevation: f32,
223        shape: LayerShape,
224        clip: bool,
225        ambient_color: Color,
226        spot_color: Color,
227    ) -> Self {
228        let clamped_elevation = elevation.max(0.0);
229        if clamped_elevation == 0.0 && !clip {
230            return self;
231        }
232
233        self.graphics_layer_value(GraphicsLayer {
234            shadow_elevation: clamped_elevation,
235            ambient_shadow_color: ambient_color,
236            spot_shadow_color: spot_color,
237            shape,
238            clip,
239            ..Default::default()
240        })
241    }
242
243    /// Apply a backdrop effect to content behind this composable's bounds.
244    pub fn backdrop_effect(self, effect: RenderEffect) -> Self {
245        let layer = GraphicsLayer {
246            backdrop_effect: Some(effect),
247            ..Default::default()
248        };
249        let modifier = Self::with_element(GraphicsLayerElement::new(layer))
250            .with_inspector_metadata(inspector_metadata("backdropEffect", |info| {
251                info.add_property("enabled", "true");
252            }));
253        self.then(modifier)
254    }
255
256    /// Blur content behind this composable, clipped to the composable bounds.
257    ///
258    /// `radius` is expressed in Dp and converted to px using the current render
259    /// density when modifier slices are evaluated.
260    pub fn backdrop_blur(self, radius: Dp) -> Self {
261        if radius.0 <= 0.0 {
262            return self.clip_to_bounds();
263        }
264
265        let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(move || {
266            backdrop_blur_layer(radius, LayerShape::Rectangle)
267        })))
268        .with_inspector_metadata(inspector_metadata("backdropBlur", move |info| {
269            info.add_property("radius", radius.0.to_string());
270        }));
271        self.then(modifier)
272    }
273
274    /// Blur content behind this composable with a radius that changes across
275    /// its bounds. This is a true spatial blur gradient: the sampling kernel
276    /// interpolates from `start_radius` to `end_radius`; it is not an opacity
277    /// gradient over a uniformly blurred layer.
278    pub fn backdrop_gradient_blur(
279        self,
280        start_radius: Dp,
281        end_radius: Dp,
282        direction: GradientBlurDirection,
283    ) -> Self {
284        if start_radius.0 <= 0.0 && end_radius.0 <= 0.0 {
285            return self.clip_to_bounds();
286        }
287        let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(move || {
288            backdrop_gradient_blur_layer(start_radius, end_radius, direction)
289        })))
290        .with_inspector_metadata(inspector_metadata(
291            "backdropGradientBlur",
292            move |info| {
293                info.add_property("startRadius", start_radius.0.to_string());
294                info.add_property("endRadius", end_radius.0.to_string());
295                info.add_property("direction", format!("{direction:?}"));
296            },
297        ));
298        self.then(modifier)
299    }
300
301    /// Apply a frosted glass material: backdrop blur, clipped shape, and tint.
302    pub fn glass_material(self, material: GlassMaterial) -> Self {
303        let blur_radius = material.blur_radius;
304        let shape = material.shape;
305        let modifier = Self::with_element(LazyGraphicsLayerElement::new(Rc::new(move || {
306            backdrop_blur_layer(blur_radius, LayerShape::Rounded(shape))
307        })))
308        .with_inspector_metadata(inspector_metadata("glassMaterial", move |info| {
309            info.add_property("blurRadius", blur_radius.0.to_string());
310            info.add_property("shape", format!("{shape:?}"));
311        }));
312
313        self.then(modifier)
314            .rounded_corner_shape(material.shape)
315            .background(material.tint)
316    }
317
318    /// Convenience alias for applying a backdrop shader effect.
319    pub fn shader_background(self, shader: RuntimeShader) -> Self {
320        self.backdrop_effect(RenderEffect::runtime_shader(shader))
321    }
322
323    /// Apply a color filter to this composable's graphics layer output.
324    ///
325    /// This mirrors Compose's `graphicsLayer(colorFilter = ...)` capability.
326    pub fn color_filter(self, filter: ColorFilter) -> Self {
327        let layer = GraphicsLayer {
328            color_filter: Some(filter),
329            ..Default::default()
330        };
331        let modifier = Self::with_element(GraphicsLayerElement::new(layer))
332            .with_inspector_metadata(inspector_metadata("colorFilter", |info| {
333                info.add_property("enabled", "true");
334            }));
335        self.then(modifier)
336    }
337
338    /// Convenience color filter that tints layer output.
339    pub fn tint(self, tint: Color) -> Self {
340        self.color_filter(ColorFilter::tint(tint))
341    }
342
343    /// Configures how the layer is composited into its parent.
344    pub fn compositing_strategy(self, strategy: CompositingStrategy) -> Self {
345        self.graphics_layer_value(GraphicsLayer {
346            compositing_strategy: strategy,
347            ..Default::default()
348        })
349    }
350
351    /// Configures blend mode for this layer output.
352    ///
353    /// Runtime support is backend-dependent. Current renderers fully support
354    /// `SrcOver` and `DstOut`; unsupported modes fall back to `SrcOver`.
355    pub fn layer_blend_mode(self, blend_mode: BlendMode) -> Self {
356        self.graphics_layer_value(GraphicsLayer {
357            blend_mode,
358            ..Default::default()
359        })
360    }
361
362    /// Apply a directional gradient cut mask to this composable output.
363    ///
364    /// This masks the rendered layer with rounded corners and a feathered edge.
365    pub fn gradient_cut_mask(
366        self,
367        area_width: f32,
368        area_height: f32,
369        spec: GradientCutMaskSpec,
370    ) -> Self {
371        let layer = GraphicsLayer {
372            render_effect: Some(gradient_cut_mask_effect(&spec, area_width, area_height)),
373            ..Default::default()
374        };
375        self.graphics_layer_value(layer)
376    }
377
378    /// Apply a rounded alpha mask to this composable output.
379    ///
380    /// Useful to constrain a preceding render effect (for example blur) to a
381    /// rounded shape while preserving a soft edge transition.
382    pub fn rounded_alpha_mask(
383        self,
384        area_width: f32,
385        area_height: f32,
386        corner_radius: f32,
387        edge_feather: f32,
388    ) -> Self {
389        let has_radius = corner_radius.is_finite() && corner_radius > 0.0;
390        let has_feather = edge_feather.is_finite() && edge_feather > 0.0;
391        if !has_radius && !has_feather {
392            return self;
393        }
394        let layer = GraphicsLayer {
395            render_effect: Some(rounded_alpha_mask_effect(
396                area_width,
397                area_height,
398                corner_radius,
399                edge_feather,
400            )),
401            ..Default::default()
402        };
403        self.graphics_layer_value(layer)
404    }
405
406    /// Apply a directional gradient fade mask with destination-out semantics.
407    ///
408    /// This mirrors Compose's `drawWithContent + drawRect(..., BlendMode.DstOut)`
409    /// pattern for fading content to transparent along one axis.
410    pub fn gradient_fade_dst_out(
411        self,
412        area_width: f32,
413        area_height: f32,
414        spec: GradientFadeMaskSpec,
415    ) -> Self {
416        let layer = GraphicsLayer {
417            render_effect: Some(gradient_fade_dst_out_effect(&spec, area_width, area_height)),
418            ..Default::default()
419        };
420        self.graphics_layer_value(layer)
421    }
422}
423
424/// Visual parameters for [`Modifier::glass_material`].
425#[derive(Clone, Copy, Debug, PartialEq)]
426pub struct GlassMaterial {
427    pub blur_radius: Dp,
428    pub tint: Color,
429    pub shape: RoundedCornerShape,
430}
431
432impl GlassMaterial {
433    pub fn new(blur_radius: Dp, tint: Color, shape: RoundedCornerShape) -> Self {
434        Self {
435            blur_radius,
436            tint,
437            shape,
438        }
439    }
440}