use crate::core::{Property, UsesProperty, Widget};
use crate::imaging::{BlurredRoundedRect, Composite, Painter};
use crate::kurbo::{Affine, BezPath, Insets, Point, RoundedRect, Shape as _};
use crate::layout::Length;
use crate::peniko::color::{AlphaColor, Srgb};
impl<W: Widget> UsesProperty<BoxShadow> for W {}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoxShadow {
pub color: AlphaColor<Srgb>,
pub offset: Point,
pub blur_radius: Length,
}
impl Property for BoxShadow {
fn static_default() -> &'static Self {
static DEFAULT: BoxShadow = BoxShadow {
color: AlphaColor::TRANSPARENT,
offset: Point::ZERO,
blur_radius: Length::ZERO,
};
&DEFAULT
}
}
impl Default for BoxShadow {
fn default() -> Self {
*Self::static_default()
}
}
impl BoxShadow {
pub fn new(color: AlphaColor<Srgb>, offset: impl Into<Point>) -> Self {
Self {
color,
offset: offset.into(),
blur_radius: Length::ZERO,
}
}
pub const fn blur(self, blur_radius: Length) -> Self {
Self {
blur_radius,
..self
}
}
pub const fn is_visible(&self) -> bool {
let alpha = self.color.components[3];
alpha != 0.0
}
pub fn paint(&self, painter: &mut Painter<'_>, transform: Affine, rect: RoundedRect) {
if !self.is_visible() {
return;
}
let transform = transform.pre_translate(self.offset.to_vec2());
let blur_radius = self.blur_radius.get();
let radius = (rect.radii().bottom_left
+ rect.radii().bottom_right
+ rect.radii().top_left
+ rect.radii().top_right)
/ 4.;
let std_dev = blur_radius;
let kernel_size = 2.5 * std_dev;
let carve_out_rect = rect - self.offset.to_vec2();
let big_rect = rect.rect().inflate(kernel_size, kernel_size);
let clip_shape = BezPath::from_iter(
big_rect
.path_elements(0.1)
.chain(carve_out_rect.to_path(0.1).reverse_subpaths()),
);
painter.with_fill_clip_transformed(clip_shape, transform, |painter| {
painter.blurred_rounded_rect(BlurredRoundedRect {
transform,
rect: rect.rect(),
color: self.color,
radius,
std_dev: blur_radius,
composite: Composite::default(),
});
});
}
pub fn get_insets(&self) -> Insets {
let blur_radius = self.blur_radius.get();
Insets {
x0: (blur_radius - self.offset.x).max(0.),
y0: (blur_radius - self.offset.y).max(0.),
x1: (blur_radius + self.offset.x).max(0.),
y1: (blur_radius + self.offset.y).max(0.),
}
}
}