use std::sync::Arc;
use crate::style::{BorderStyle, Color};
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct BoxShadow {
pub offset_x: f32,
pub offset_y: f32,
pub blur: f32,
pub spread: f32,
pub color: Color,
pub inset: bool,
}
impl BoxShadow {
pub fn is_visible(&self) -> bool {
!self.color.is_transparent()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GradientSize {
ClosestSide,
ClosestCorner,
FarthestSide,
FarthestCorner,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientKind {
Linear {
angle: f32,
},
LinearCorner {
right: bool,
bottom: bool,
},
Radial {
circle: bool,
size: GradientSize,
x: f32,
y: f32,
},
Conic {
from: f32,
x: f32,
y: f32,
},
}
impl GradientKind {
pub fn linear_angle(&self, w: f32, h: f32) -> Option<f32> {
match *self {
GradientKind::Linear { angle } => Some(angle),
GradientKind::LinearCorner { right, bottom } => {
let a = (h.max(f32::EPSILON) / w.max(f32::EPSILON))
.atan()
.to_degrees();
Some(match (right, bottom) {
(true, false) => 90.0 - a,
(true, true) => 90.0 + a,
(false, true) => 270.0 - a,
(false, false) => 270.0 + a,
})
}
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorStop {
pub color: Color,
pub position: Option<f32>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Gradient {
pub kind: GradientKind,
pub stops: Vec<ColorStop>,
pub repeating: bool,
}
impl Gradient {
pub fn resolved_stops(&self) -> Vec<(Color, f32)> {
let n = self.stops.len();
let mut pos: Vec<Option<f32>> = self.stops.iter().map(|s| s.position).collect();
if pos[0].is_none() {
pos[0] = Some(0.0);
}
if pos[n - 1].is_none() {
pos[n - 1] = Some(1.0);
}
let mut max = 0.0f32;
for p in pos.iter_mut().flatten() {
max = max.max(*p);
*p = max;
}
let mut i = 0;
while i < n {
if pos[i].is_some() {
i += 1;
continue;
}
let start = i - 1;
let mut end = i;
while pos[end].is_none() {
end += 1;
}
let (a, b) = (pos[start].unwrap_or(0.0), pos[end].unwrap_or(1.0));
for (k, p) in pos.iter_mut().enumerate().take(end).skip(i) {
*p = Some(a + (b - a) * (k - start) as f32 / (end - start) as f32);
}
i = end;
}
self.stops
.iter()
.zip(pos)
.map(|(s, p)| (s.color, p.unwrap_or(0.0)))
.collect()
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Filter {
Blur(f32),
Brightness(f32),
Contrast(f32),
Grayscale(f32),
HueRotate(f32),
Invert(f32),
Opacity(f32),
Saturate(f32),
Sepia(f32),
DropShadow {
offset_x: f32,
offset_y: f32,
blur: f32,
color: Color,
},
}
impl Filter {
pub fn color_matrix(&self) -> Option<[f32; 20]> {
let id = |r: [f32; 3], g: [f32; 3], b: [f32; 3]| {
[
r[0], r[1], r[2], 0.0, 0.0, g[0], g[1], g[2], 0.0, 0.0, b[0], b[1], b[2], 0.0, 0.0,
0.0, 0.0, 0.0, 1.0, 0.0,
]
};
Some(match *self {
Filter::Brightness(v) => id([v, 0.0, 0.0], [0.0, v, 0.0], [0.0, 0.0, v]),
Filter::Contrast(v) => {
let t = (1.0 - v) / 2.0;
[
v, 0.0, 0.0, 0.0, t, 0.0, v, 0.0, 0.0, t, 0.0, 0.0, v, 0.0, t, 0.0, 0.0, 0.0,
1.0, 0.0,
]
}
Filter::Grayscale(v) => {
let a = 1.0 - v;
id(
[
0.2126 + 0.7874 * a,
0.7152 - 0.7152 * a,
0.0722 - 0.0722 * a,
],
[
0.2126 - 0.2126 * a,
0.7152 + 0.2848 * a,
0.0722 - 0.0722 * a,
],
[
0.2126 - 0.2126 * a,
0.7152 - 0.7152 * a,
0.0722 + 0.9278 * a,
],
)
}
Filter::Sepia(v) => {
let a = 1.0 - v;
id(
[0.393 + 0.607 * a, 0.769 - 0.769 * a, 0.189 - 0.189 * a],
[0.349 - 0.349 * a, 0.686 + 0.314 * a, 0.168 - 0.168 * a],
[0.272 - 0.272 * a, 0.534 - 0.534 * a, 0.131 + 0.869 * a],
)
}
Filter::Saturate(s) => id(
[0.213 + 0.787 * s, 0.715 - 0.715 * s, 0.072 - 0.072 * s],
[0.213 - 0.213 * s, 0.715 + 0.285 * s, 0.072 - 0.072 * s],
[0.213 - 0.213 * s, 0.715 - 0.715 * s, 0.072 + 0.928 * s],
),
Filter::HueRotate(deg) => {
let (s, c) = deg.to_radians().sin_cos();
id(
[
0.213 + c * 0.787 - s * 0.213,
0.715 - c * 0.715 - s * 0.715,
0.072 - c * 0.072 + s * 0.928,
],
[
0.213 - c * 0.213 + s * 0.143,
0.715 + c * 0.285 + s * 0.140,
0.072 - c * 0.072 - s * 0.283,
],
[
0.213 - c * 0.213 - s * 0.787,
0.715 - c * 0.715 + s * 0.715,
0.072 + c * 0.928 + s * 0.072,
],
)
}
Filter::Invert(v) => {
let m = 1.0 - 2.0 * v;
[
m, 0.0, 0.0, 0.0, v, 0.0, m, 0.0, 0.0, v, 0.0, 0.0, m, 0.0, v, 0.0, 0.0, 0.0,
1.0, 0.0,
]
}
Filter::Opacity(v) => [
1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, v, 0.0,
],
Filter::Blur(_) | Filter::DropShadow { .. } => return None,
})
}
}
pub fn compose_color_matrices(filters: &[Filter]) -> Option<[f32; 20]> {
let mut out: Option<[f32; 20]> = None;
for m in filters.iter().filter_map(Filter::color_matrix) {
out = Some(match out {
None => m,
Some(prev) => {
let mut r = [0.0; 20];
for row in 0..4 {
for col in 0..5 {
let mut v = if col == 4 { m[row * 5 + 4] } else { 0.0 };
for k in 0..4 {
v += m[row * 5 + k] * prev[k * 5 + col];
}
r[row * 5 + col] = v;
}
}
r
}
});
}
out
}
pub fn blur_radius(filters: &[Filter]) -> f32 {
filters
.iter()
.map(|f| match f {
Filter::Blur(r) => *r,
_ => 0.0,
})
.sum()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[allow(missing_docs)]
pub enum BlendMode {
#[default]
Normal,
Multiply,
Screen,
Overlay,
Darken,
Lighten,
ColorDodge,
ColorBurn,
HardLight,
SoftLight,
Difference,
Exclusion,
Hue,
Saturation,
Color,
Luminosity,
PlusDarker,
PlusLighter,
}
impl BlendMode {
pub fn name(self) -> &'static str {
match self {
BlendMode::Normal => "normal",
BlendMode::Multiply => "multiply",
BlendMode::Screen => "screen",
BlendMode::Overlay => "overlay",
BlendMode::Darken => "darken",
BlendMode::Lighten => "lighten",
BlendMode::ColorDodge => "color-dodge",
BlendMode::ColorBurn => "color-burn",
BlendMode::HardLight => "hard-light",
BlendMode::SoftLight => "soft-light",
BlendMode::Difference => "difference",
BlendMode::Exclusion => "exclusion",
BlendMode::Hue => "hue",
BlendMode::Saturation => "saturation",
BlendMode::Color => "color",
BlendMode::Luminosity => "luminosity",
BlendMode::PlusDarker => "plus-darker",
BlendMode::PlusLighter => "plus-lighter",
}
}
pub fn parse(s: &str) -> Option<BlendMode> {
Some(match s {
"normal" => BlendMode::Normal,
"multiply" => BlendMode::Multiply,
"screen" => BlendMode::Screen,
"overlay" => BlendMode::Overlay,
"darken" => BlendMode::Darken,
"lighten" => BlendMode::Lighten,
"color-dodge" => BlendMode::ColorDodge,
"color-burn" => BlendMode::ColorBurn,
"hard-light" => BlendMode::HardLight,
"soft-light" => BlendMode::SoftLight,
"difference" => BlendMode::Difference,
"exclusion" => BlendMode::Exclusion,
"hue" => BlendMode::Hue,
"saturation" => BlendMode::Saturation,
"color" => BlendMode::Color,
"luminosity" => BlendMode::Luminosity,
"plus-darker" => BlendMode::PlusDarker,
"plus-lighter" => BlendMode::PlusLighter,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Outline {
pub width: f32,
pub color: Color,
pub style: BorderStyle,
pub offset: f32,
}
impl Outline {
pub const NONE: Outline = Outline {
width: 0.0,
color: Color::BLACK,
style: BorderStyle::Solid,
offset: 0.0,
};
pub fn is_visible(&self) -> bool {
self.width > 0.0 && !self.color.is_transparent()
}
}
impl Default for Outline {
fn default() -> Self {
Self::NONE
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[allow(missing_docs)]
pub enum Cursor {
#[default]
Auto,
Default,
Pointer,
Text,
Wait,
Progress,
Help,
Crosshair,
Move,
Grab,
Grabbing,
NotAllowed,
ZoomIn,
ZoomOut,
ColResize,
RowResize,
None,
}
impl Cursor {
pub fn parse(s: &str) -> Option<Cursor> {
Some(match s {
"auto" => Cursor::Auto,
"default" | "context-menu" | "alias" | "copy" | "cell" => Cursor::Default,
"pointer" => Cursor::Pointer,
"text" | "vertical-text" => Cursor::Text,
"wait" => Cursor::Wait,
"progress" => Cursor::Progress,
"help" => Cursor::Help,
"crosshair" => Cursor::Crosshair,
"move" | "all-scroll" => Cursor::Move,
"grab" => Cursor::Grab,
"grabbing" => Cursor::Grabbing,
"not-allowed" | "no-drop" => Cursor::NotAllowed,
"zoom-in" => Cursor::ZoomIn,
"zoom-out" => Cursor::ZoomOut,
"col-resize" | "e-resize" | "w-resize" | "ew-resize" => Cursor::ColResize,
"row-resize" | "n-resize" | "s-resize" | "ns-resize" => Cursor::RowResize,
"ne-resize" | "nw-resize" | "se-resize" | "sw-resize" | "nesw-resize"
| "nwse-resize" => Cursor::Move,
"none" => Cursor::None,
_ => return None,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TransitionProps(pub u8);
impl TransitionProps {
pub const COLORS: u8 = 1;
pub const OPACITY: u8 = 2;
pub const TRANSFORM: u8 = 4;
pub const SHADOW: u8 = 8;
pub const SHAPE: u8 = 16;
pub const ALL: u8 = 0x1f;
#[inline]
pub fn has(self, group: u8) -> bool {
self.0 & group != 0
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Transition {
pub properties: TransitionProps,
pub duration: f32,
pub delay: f32,
pub easing: [f32; 4],
}
impl Transition {
pub const EASE: [f32; 4] = [0.25, 0.1, 0.25, 1.0];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Keyframes {
Spin,
Ping,
Pulse,
Bounce,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KeyframeAnimation {
pub keyframes: Keyframes,
pub duration: f32,
pub delay: f32,
pub easing: [f32; 4],
pub iterations: Option<u32>,
}
impl KeyframeAnimation {
pub const fn new(keyframes: Keyframes) -> Self {
Self {
keyframes,
duration: 1000.0,
delay: 0.0,
easing: [0.0, 0.0, 1.0, 1.0],
iterations: None,
}
}
pub const fn duration(mut self, ms: f32) -> Self {
self.duration = ms;
self
}
pub const fn delay(mut self, ms: f32) -> Self {
self.delay = ms;
self
}
pub const fn easing(mut self, curve: [f32; 4]) -> Self {
self.easing = curve;
self
}
pub const fn iterations(mut self, count: u32) -> Self {
self.iterations = Some(count);
self
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Effects {
pub box_shadows: Vec<BoxShadow>,
pub background_images: Vec<Gradient>,
pub filters: Vec<Filter>,
pub backdrop_filters: Vec<Filter>,
}
impl Effects {
pub fn is_empty(&self) -> bool {
self.box_shadows.is_empty()
&& self.background_images.is_empty()
&& self.filters.is_empty()
&& self.backdrop_filters.is_empty()
}
}
pub(crate) fn shared(effects: Effects) -> Option<Arc<Effects>> {
(!effects.is_empty()).then(|| Arc::new(effects))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn stops_spread_evenly() {
let c = Color::BLACK;
let g = Gradient {
kind: GradientKind::Linear { angle: 90.0 },
stops: vec![
ColorStop {
color: c,
position: None,
},
ColorStop {
color: c,
position: None,
},
ColorStop {
color: c,
position: Some(0.8),
},
ColorStop {
color: c,
position: Some(0.5),
},
],
repeating: false,
};
let p: Vec<f32> = g.resolved_stops().into_iter().map(|(_, p)| p).collect();
assert_eq!(p, [0.0, 0.4, 0.8, 0.8]);
}
#[test]
fn matrices_compose_in_order() {
let m = compose_color_matrices(&[Filter::Invert(1.0), Filter::Brightness(0.5)]).unwrap();
let apply = |c: f32| m[0] * c + m[4];
assert!((apply(1.0) - 0.0).abs() < 1e-6);
assert!((apply(0.0) - 0.5).abs() < 1e-6);
assert!(compose_color_matrices(&[Filter::Blur(2.0)]).is_none());
}
#[test]
fn corner_angles() {
let k = GradientKind::LinearCorner {
right: true,
bottom: false,
};
assert!((k.linear_angle(100.0, 100.0).unwrap() - 45.0).abs() < 1e-4);
let k = GradientKind::LinearCorner {
right: true,
bottom: true,
};
assert!((k.linear_angle(100.0, 100.0).unwrap() - 135.0).abs() < 1e-4);
}
}