use crate::paint::rounded::{CornerShape, Radii};
use crate::paint::{
Backgrounds, BorderImage, BoxShadow, Clip, Color, Contour, Fill, LengthPercentage, Point, Rect,
Segment, Shape,
};
use serde::Serialize;
use std::{
convert::Infallible,
sync::{Arc, LazyLock},
};
const DOT_SPACING_WIDTHS: f32 = 2.0;
pub(crate) const DASH_LENGTH_WIDTHS: f32 = 3.0;
pub(crate) const DASH_GAP_WIDTHS: f32 = 2.0;
static INITIAL_CORNER_SHAPES: LazyLock<Arc<[CornerShape; 4]>> =
LazyLock::new(|| Arc::new([CornerShape::ROUND; 4]));
static INITIAL_RADII: LazyLock<Arc<[[LengthPercentage; 2]; 4]>> =
LazyLock::new(|| Arc::new(std::array::from_fn(|_| [LengthPercentage::ZERO; 2])));
pub(crate) fn dot_gap(length: f32, width: f32) -> f32 {
let nominal = DOT_SPACING_WIDTHS * width;
let intervals = (length / nominal).floor();
if intervals < 1.0 {
nominal
} else {
(length / intervals).max(nominal)
}
}
pub(crate) fn dash_gap(length: f32, width: f32) -> f32 {
let dash = DASH_LENGTH_WIDTHS * width;
let nominal = DASH_GAP_WIDTHS * width;
let gaps = ((length - dash) / (dash + nominal)).floor();
if gaps < 1.0 {
nominal
} else {
(length - (gaps + 1.0) * dash) / gaps
}
}
pub(crate) const DEFAULT_BORDER_WIDTH: f32 = 1.6875;
const SIDE_ORDER: [usize; 4] = [3, 0, 1, 2];
pub(crate) fn side_runs(
widths: [f32; 4],
joined: impl Fn(usize, usize) -> bool,
) -> Vec<Vec<usize>> {
let start = if let Some(absent) = SIDE_ORDER.iter().find(|side| widths[**side] <= 0.0) {
(absent + 1) % 4
} else {
let mut start = SIDE_ORDER[0];
for _ in 1..SIDE_ORDER.len() {
let previous = (start + 3) % 4;
if !joined(previous, start) {
break;
}
start = previous;
}
start
};
let mut runs: Vec<Vec<usize>> = Vec::new();
for side in (0..4).map(|offset| (start + offset) % 4) {
if widths[side] <= 0.0 {
continue;
}
match runs.last_mut() {
Some(run)
if (run[run.len() - 1] + 1) % 4 == side && joined(run[run.len() - 1], side) =>
{
run.push(side);
}
_ => runs.push(vec![side]),
}
}
runs
}
pub(crate) fn ring<I>(decoration: &BoxDecoration<I>, widths: [f32; 4]) -> Option<Vec<f32>> {
let first = decoration.borders[0];
let uniform = widths.iter().all(|width| *width > 0.0)
&& decoration
.borders
.iter()
.all(|border| border.style == first.style && border.color == first.color);
if !uniform {
return None;
}
match first.style {
BorderStyle::Solid => Some(vec![0.0, 1.0]),
BorderStyle::Double => Some(vec![0.0, DOUBLE_LINE, 1.0 - DOUBLE_LINE, 1.0]),
_ => None,
}
}
fn ring_corners(rect: Rect, widths: [f32; 4], t: f32) -> [Point; 4] {
let [top, right, bottom, left] = widths.map(|width| width * t);
[
[rect.x + left, rect.y + top],
[rect.x + rect.width - right, rect.y + top],
[rect.x + rect.width - right, rect.y + rect.height - bottom],
[rect.x + left, rect.y + rect.height - bottom],
]
}
const DOUBLE_LINE: f32 = 1.0 / 3.0;
const GROOVE_SPLIT: f32 = 0.5;
const CHANNEL_MAX: u16 = 255;
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Band {
pub from: f32,
pub to: f32,
pub color: Color,
}
pub(crate) fn shade(color: Color, light: bool) -> Color {
Color {
rgb: color.rgb.map(|channel| {
let base = if light { CHANNEL_MAX } else { 0 };
(u16::from(channel) + base).div_ceil(2) as u8
}),
alpha: color.alpha,
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub enum BorderStyle {
#[default]
None,
Hidden,
Solid,
Dotted,
Dashed,
Double,
Groove,
Ridge,
Inset,
Outset,
}
impl BorderStyle {
pub fn suppresses_width(self) -> bool {
matches!(self, Self::None | Self::Hidden)
}
#[must_use]
pub fn collapsed(self) -> Self {
match self {
Self::Inset => Self::Ridge,
Self::Outset => Self::Groove,
style => style,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct Border {
pub width: f32,
pub style: BorderStyle,
pub color: Color,
}
impl Default for Border {
fn default() -> Self {
Self {
width: DEFAULT_BORDER_WIDTH,
style: BorderStyle::None,
color: Color::BLACK,
}
}
}
impl Border {
pub fn used_width(self) -> f32 {
if self.style.suppresses_width() {
0.0
} else {
self.width
}
}
pub(crate) fn bands(self, side: usize) -> Vec<Band> {
let top_left = side == 0 || side == 3;
let band = |from, to, color| Band { from, to, color };
let color = self.color;
match self.style {
BorderStyle::Solid => vec![band(0.0, 1.0, color)],
BorderStyle::Double => vec![
band(0.0, DOUBLE_LINE, color),
band(1.0 - DOUBLE_LINE, 1.0, color),
],
BorderStyle::Groove | BorderStyle::Ridge => {
let outer_light = (self.style == BorderStyle::Ridge) == top_left;
vec![
band(0.0, GROOVE_SPLIT, shade(color, outer_light)),
band(GROOVE_SPLIT, 1.0, shade(color, !outer_light)),
]
}
BorderStyle::Inset | BorderStyle::Outset => {
let light = (self.style == BorderStyle::Outset) == top_left;
vec![band(0.0, 1.0, shade(color, light))]
}
BorderStyle::None | BorderStyle::Hidden | BorderStyle::Dotted | BorderStyle::Dashed => {
Vec::new()
}
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum OutlineStyle {
Auto,
Line(BorderStyle),
}
impl Default for OutlineStyle {
fn default() -> Self {
Self::Line(BorderStyle::None)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct Outline {
pub width: f32,
pub style: OutlineStyle,
pub color: Color,
pub offset: f32,
}
impl Default for Outline {
fn default() -> Self {
Self {
width: DEFAULT_BORDER_WIDTH,
style: OutlineStyle::default(),
color: Color::BLACK,
offset: 0.0,
}
}
}
impl Outline {
pub fn computed_width(self) -> f32 {
match self.style {
OutlineStyle::Line(style) if style.suppresses_width() => 0.0,
OutlineStyle::Auto | OutlineStyle::Line(_) => self.width,
}
}
pub fn used_width(self) -> f32 {
match self.style {
OutlineStyle::Auto => DEFAULT_BORDER_WIDTH,
OutlineStyle::Line(_) => self.computed_width(),
}
}
pub fn is_drawn(self) -> bool {
self.used_width() > 0.0 && self.color.alpha > 0.0
}
fn line_style(self) -> BorderStyle {
match self.style {
OutlineStyle::Auto => BorderStyle::Solid,
OutlineStyle::Line(style) => style,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub struct BoxDecoration<I = Infallible> {
pub background: Color,
pub backgrounds: Arc<Backgrounds<I>>,
pub borders: [Border; 4],
pub radii: Arc<[[LengthPercentage; 2]; 4]>,
pub corner_shapes: Arc<[CornerShape; 4]>,
pub shadows: Arc<Vec<BoxShadow>>,
pub border_image: Arc<BorderImage<I>>,
pub outline: Outline,
pub masks: Arc<crate::paint::Masks<I>>,
}
impl<I> Default for BoxDecoration<I> {
fn default() -> Self {
Self {
background: Color::TRANSPARENT,
backgrounds: Arc::default(),
borders: [Border::default(); 4],
radii: INITIAL_RADII.clone(),
corner_shapes: INITIAL_CORNER_SHAPES.clone(),
shadows: Arc::default(),
border_image: Arc::default(),
outline: Outline::default(),
masks: Arc::default(),
}
}
}
impl<I> BoxDecoration<I> {
pub fn is_visible(&self) -> bool {
self.background.alpha > 0.0
|| self.backgrounds.has_images()
|| self.has_shadows()
|| self.border_image.is_drawn()
|| self.outline.is_drawn()
|| self
.borders
.iter()
.any(|b| b.used_width() > 0.0 && b.color.alpha > 0.0)
}
pub(crate) fn has_shadows(&self) -> bool {
self.shadows.iter().any(|shadow| shadow.color.alpha > 0.0)
}
pub fn resolve_images<E>(
&mut self,
rendering: crate::paint::ImageRendering,
mut load: impl FnMut(&crate::paint::ImageReference<'_>) -> Result<Option<I>, E>,
) -> Result<(), E>
where
I: Clone,
{
Backgrounds::resolve_images(&mut self.backgrounds, rendering, &mut load)?;
if self
.masks
.layers
.images
.iter()
.any(crate::paint::BackgroundImage::needs_loading)
{
Backgrounds::resolve_images(
&mut Arc::make_mut(&mut self.masks).layers,
rendering,
&mut load,
)?;
}
if self.masks.border.source.needs_loading() {
Arc::make_mut(&mut Arc::make_mut(&mut self.masks).border)
.source
.load(rendering, &mut load)?;
}
if self.border_image.source.needs_loading() {
Arc::make_mut(&mut self.border_image)
.source
.load(rendering, &mut load)?;
}
Ok(())
}
pub fn clear_background(&mut self) {
self.background = Color::TRANSPARENT;
self.backgrounds = Arc::default();
}
}
impl BoxDecoration<Infallible> {
pub fn with_image_type<I>(&self) -> BoxDecoration<I> {
BoxDecoration {
background: self.background,
backgrounds: Arc::new(self.backgrounds.with_image_type()),
masks: Arc::new(self.masks.with_image_type()),
borders: self.borders,
radii: self.radii.clone(),
corner_shapes: self.corner_shapes.clone(),
shadows: self.shadows.clone(),
border_image: Arc::new(self.border_image.with_image_type()),
outline: self.outline,
}
}
pub fn load_images<I: Clone, E>(
&self,
rendering: crate::paint::ImageRendering,
load: impl FnMut(&crate::paint::ImageReference<'_>) -> Result<Option<I>, E>,
) -> Result<BoxDecoration<I>, E> {
let mut decoration = self.with_image_type();
decoration.resolve_images(rendering, load)?;
Ok(decoration)
}
}
pub const INLINE_EDGES: [bool; 2] = [true; 2];
#[derive(Clone, Copy, Debug, Serialize)]
pub struct BoxAreas<T> {
pub border: T,
pub padding: T,
pub content: T,
}
impl BoxAreas<Rect> {
pub(crate) fn single(rect: Rect) -> Self {
Self {
border: rect,
padding: rect,
content: rect,
}
}
}
impl<T: Clone> BoxAreas<T> {
pub fn area(&self, area: crate::paint::BoxArea) -> T {
match area {
crate::paint::BoxArea::BorderBox => self.border.clone(),
crate::paint::BoxArea::PaddingBox => self.padding.clone(),
crate::paint::BoxArea::ContentBox => self.content.clone(),
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct BackgroundGeometry {
pub origins: Option<BoxAreas<Rect>>,
pub clips: BoxAreas<Clip>,
pub viewport: Option<Rect>,
}
#[expect(
clippy::trivially_copy_pass_by_ref,
reason = "serde skip_serializing_if passes the field by reference"
)]
fn background_enabled(enabled: &bool) -> bool {
*enabled
}
#[derive(Clone, Debug, Serialize)]
#[serde(bound(serialize = ""))]
pub struct BoxPaint<I = Infallible> {
pub rect: Rect,
#[serde(skip_serializing_if = "Option::is_none")]
pub border_geometry: Option<Arc<BorderGeometry>>,
pub decoration: BoxDecoration<I>,
pub padding: [f32; 4],
pub margins: [f32; 4],
pub background_box: Option<Rect>,
#[serde(skip_serializing_if = "Option::is_none")]
pub background_geometry: Option<Arc<BackgroundGeometry>>,
#[serde(skip_serializing_if = "background_enabled")]
pub draw_background: bool,
pub first_fragment: bool,
pub last_fragment: bool,
pub inline_edges: [bool; 2],
#[serde(skip_serializing_if = "Option::is_none")]
pub legend: Option<LegendCut>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_area: Option<Arc<crate::graphics::FlowPaint>>,
}
impl<I: Clone> BoxPaint<I> {
pub(crate) fn unpainted(&self) -> Self {
let mut decoration = BoxDecoration {
radii: self.decoration.radii.clone(),
corner_shapes: self.decoration.corner_shapes.clone(),
borders: self.decoration.borders,
..BoxDecoration::default()
};
for border in &mut decoration.borders {
border.color = Color::TRANSPARENT;
}
Self {
decoration,
draw_background: false,
text_area: None,
..self.clone()
}
}
}
#[derive(Clone, Debug, Serialize)]
pub struct BorderGeometry {
pub rect: Rect,
pub radii: Radii,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct LegendCut {
pub side: usize,
pub inset: f32,
pub gap: [f32; 2],
}
impl<I> BoxPaint<I> {
pub fn whole(rect: Rect, decoration: BoxDecoration<I>) -> Self {
Self {
rect,
border_geometry: None,
decoration,
padding: [0.0; 4],
margins: [0.0; 4],
background_box: None,
background_geometry: None,
draw_background: true,
first_fragment: true,
last_fragment: true,
inline_edges: INLINE_EDGES,
legend: None,
text_area: None,
}
}
pub(crate) fn sliced(&self) -> [bool; 4] {
[
!self.first_fragment,
!self.inline_edges[1],
!self.last_fragment,
!self.inline_edges[0],
]
}
fn widths(&self) -> [f32; 4] {
let mut widths = self.decoration.borders.map(Border::used_width);
for (width, sliced) in widths.iter_mut().zip(self.sliced()) {
if sliced {
*width = 0.0;
}
}
widths
}
pub fn assembled_box(&self) -> Option<Rect> {
self.background_box
.filter(|_| self.sliced().contains(&true))
}
pub(crate) fn decoration_rect(&self) -> Rect {
self.assembled_box().unwrap_or(self.rect)
}
fn decoration_widths(&self) -> [f32; 4] {
if self.assembled_box().is_some() {
self.decoration.borders.map(Border::used_width)
} else {
self.widths()
}
}
pub(crate) fn slice_bounds(&self, coverage: Rect) -> Rect {
let [top, right, bottom, left] = self.sliced();
let x = if left {
coverage.x.max(self.rect.x)
} else {
coverage.x
};
let y = if top {
coverage.y.max(self.rect.y)
} else {
coverage.y
};
let end_x = coverage.x + coverage.width;
let end_y = coverage.y + coverage.height;
Rect {
x,
y,
width: ((if right {
end_x.min(self.rect.x + self.rect.width)
} else {
end_x
}) - x)
.max(0.0),
height: ((if bottom {
end_y.min(self.rect.y + self.rect.height)
} else {
end_y
}) - y)
.max(0.0),
}
}
pub(crate) fn slice_clip(&self, mut clip: Clip) -> Clip {
if self.assembled_box().is_some() {
let visible = self.slice_bounds(clip.rect);
if visible != clip.rect {
clip.reference_box = Some(clip.rect);
clip.rect = visible;
}
}
clip
}
pub(crate) fn fragment_areas(&self) -> BoxAreas<Rect> {
let sliced = self.sliced();
let padding = std::array::from_fn(|side| {
if sliced[side] {
0.0
} else {
self.padding[side]
}
});
let (padding_box, _) =
crate::paint::rounded::inset(self.rect, Radii::default(), self.widths());
let (content, _) = crate::paint::rounded::inset(padding_box, Radii::default(), padding);
BoxAreas {
border: self.rect,
padding: padding_box,
content,
}
}
pub(crate) fn inner_widths(&self) -> [f32; 4] {
let rect = self.decoration_rect();
let widths = self.decoration_widths();
let horizontal = (rect.width / (widths[1] + widths[3])).min(1.0);
let vertical = (rect.height / (widths[0] + widths[2])).min(1.0);
[
widths[0] * vertical,
widths[1] * horizontal,
widths[2] * vertical,
widths[3] * horizontal,
]
}
pub fn inner_clip(&self, padding: [f32; 4], axes: [bool; 2]) -> Clip {
let widths = self.inner_widths();
self.box_clip(
std::array::from_fn(|side| widths[side] + padding[side]),
axes,
)
}
pub(crate) fn box_clip(&self, insets: [f32; 4], axes: [bool; 2]) -> Clip {
let source = self.decoration_rect();
let radii = self.radii();
let shapes = *self.decoration.corner_shapes;
let outline = (axes == [true; 2] && shapes != [CornerShape::ROUND; 4]).then(|| {
Arc::new(crate::paint::rounded::box_contours(
source,
radii,
shapes.map(CornerShape::curvature),
insets,
))
});
let (rect, mut radii) = crate::paint::rounded::inset(source, radii, insets);
if axes != [true; 2] {
radii = Radii::default();
}
self.slice_clip(Clip {
rect,
radii,
outline,
reference_box: None,
axes,
})
}
pub fn overflow_clip_edge(
&self,
area: crate::paint::BoxArea,
margin: f32,
axes: [bool; 2],
) -> Clip {
self.overflow_clip_sides([(area, margin); 4], axes)
}
pub(crate) fn overflow_clip_sides(
&self,
margins: [(crate::paint::BoxArea, f32); 4],
axes: [bool; 2],
) -> Clip {
let widths = self.inner_widths();
let padding = self.fragment_padding();
self.inner_clip(
std::array::from_fn(|side| {
let (area, margin) = margins[side];
let edge = match area {
crate::paint::BoxArea::BorderBox => -widths[side],
crate::paint::BoxArea::PaddingBox => 0.0,
crate::paint::BoxArea::ContentBox => padding[side],
};
edge - margin
}),
axes,
)
}
pub fn has_ink(&self) -> bool {
self.rect.width > 0.0
&& self.rect.height > 0.0
&& ((self.draw_background
&& (self.decoration.background.alpha > 0.0
|| self.decoration.backgrounds.has_images()))
|| self.decoration.has_shadows()
|| self.decoration.border_image.is_drawn()
|| self.decoration.outline.is_drawn()
|| self
.widths()
.iter()
.zip(self.decoration.borders)
.any(|(width, border)| *width > 0.0 && border.color.alpha > 0.0))
}
pub(crate) fn ink(&self) -> Rect
where
I: Clone,
{
self.shadows(false)
.into_iter()
.map(|shadow| shadow.bounds)
.chain(self.outline().map(|outline| outline.rect))
.chain(self.border_image_bounds())
.fold(self.rect, Rect::union)
}
pub fn outline(&self) -> Option<Self>
where
I: Clone,
{
let outline = self.decoration.outline;
if !outline.is_drawn() {
return None;
}
let width = outline.used_width();
let growth = outline.offset + width;
let side = |start: f32, extent: f32| {
let outer = (extent + 2.0 * growth).max(2.0 * width);
(start + extent / 2.0 - outer / 2.0, outer)
};
let (x, outer_width) = side(self.rect.x, self.rect.width);
let (y, outer_height) = side(self.rect.y, self.rect.height);
let fragment = Self {
background_box: None,
..self.clone()
};
let source_radii = fragment.radii();
let radii = crate::paint::shadow::spread_radii(source_radii, growth);
let border = Border {
width,
style: outline.line_style(),
color: outline.color,
};
let mut result = Self::whole(
Rect {
x,
y,
width: outer_width,
height: outer_height,
},
BoxDecoration {
borders: [border; 4],
radii: Arc::new(radii.map(|corner| corner.map(LengthPercentage::Length))),
corner_shapes: self.decoration.corner_shapes.clone(),
..BoxDecoration::default()
},
);
if *self.decoration.corner_shapes != [CornerShape::ROUND; 4] {
result.border_geometry = Some(Arc::new(BorderGeometry {
rect: Rect {
x: self.rect.x - x,
y: self.rect.y - y,
..self.rect
},
radii: source_radii,
}));
}
Some(result)
}
pub fn radii(&self) -> Radii {
let rect = self.decoration_rect();
let sliced = self.sliced();
let radii: Radii = std::array::from_fn(|corner| {
let [horizontal, vertical] = &self.decoration.radii[corner];
let open =
self.assembled_box().is_some() || (!sliced[corner] && !sliced[(corner + 3) % 4]);
let used = [
horizontal.resolve(rect.width),
vertical.resolve(rect.height),
];
if open && used[0] > 0.0 && used[1] > 0.0 {
used
} else {
[0.0; 2]
}
});
crate::paint::rounded::constrain_corners(
radii,
[rect.width, rect.height],
self.decoration.corner_shapes.map(CornerShape::curvature),
)
}
pub fn background_fill(&self) -> Option<Fill> {
if !self.draw_background || self.decoration.background.alpha <= 0.0 {
return None;
}
let clip = self.background_clip(self.decoration.backgrounds.color_clip().area());
if clip.rect.width <= 0.0
|| clip.rect.height <= 0.0
|| clip
.outline
.as_ref()
.is_some_and(|outline| outline.is_empty())
{
return None;
}
let mut shape = if clip.outline.is_some()
|| clip
.radii
.iter()
.any(|corner| corner[0] > 0.0 && corner[1] > 0.0)
{
Shape::Path {
contours: clip.contours().into_owned(),
even_odd: false,
clip: None,
}
} else {
Shape::Rect(clip.rect)
};
if let Some(bounds) = clip.fragment_bounds() {
shape = Shape::Clipped {
shape: Box::new(shape),
bounds,
};
}
Some(Fill {
shape,
color: self.decoration.background,
})
}
pub fn border_fills(&self) -> Vec<Fill> {
let mut fills = self.uncut_border_fills();
if let Some(whole) = self.assembled_box()
&& let Some(bounds) = (Clip {
rect: self.slice_bounds(whole),
radii: Radii::default(),
outline: None,
reference_box: Some(whole),
axes: [true; 2],
})
.fragment_bounds()
{
for fill in &mut fills {
let shape = std::mem::replace(&mut fill.shape, Shape::Rect(whole));
fill.shape = Shape::Clipped {
shape: Box::new(shape),
bounds,
};
}
}
fills
}
fn uncut_border_fills(&self) -> Vec<Fill> {
let rect = self.decoration_rect();
let mut fills = Vec::new();
if rect.width <= 0.0 || rect.height <= 0.0 {
return fills;
}
let widths = self.decoration_widths();
let inner_widths = self.inner_widths();
let radii = self.radii();
if let Some(geometry) = &self.border_geometry {
let source = Rect {
x: rect.x + geometry.rect.x,
y: rect.y + geometry.rect.y,
..geometry.rect
};
return crate::paint::rounded::border_fills(
source,
&self.decoration,
widths,
inner_widths,
geometry.radii,
[
rect.y - source.y,
source.x + source.width - rect.x - rect.width,
source.y + source.height - rect.y - rect.height,
rect.x - source.x,
],
);
}
if radii.iter().any(|corner| corner[0] > 0.0) {
return crate::paint::rounded::border_fills(
rect,
&self.decoration,
widths,
inner_widths,
radii,
[0.0; 4],
);
}
let outer = ring_corners(rect, inner_widths, 0.0);
let inner = ring_corners(rect, inner_widths, 1.0);
let uniform = (self.assembled_box().is_some() || !self.sliced().contains(&true))
&& self.decoration.borders.iter().all(|border| {
border.style == self.decoration.borders[0].style
&& border.width == widths[0]
&& border.color == self.decoration.borders[0].color
})
&& widths[0] > 0.0
&& rect.width >= widths[0]
&& rect.height >= widths[0];
if uniform && self.decoration.borders[0].style == BorderStyle::Dashed {
let width = widths[0];
let half = width / 2.0;
let points = vec![
[rect.x + half, rect.y + rect.height - half],
[rect.x + rect.width - half, rect.y + rect.height - half],
[rect.x + rect.width - half, rect.y + half],
[rect.x + half, rect.y + half],
];
fills.push(Fill {
shape: Shape::Pattern {
contours: vec![Contour::polygon(&points)],
width,
dash: [DASH_LENGTH_WIDTHS * width, DASH_GAP_WIDTHS * width],
round: false,
clip: None,
},
color: self.decoration.borders[0].color,
});
return fills;
}
if let Some(boundaries) = ring(&self.decoration, widths) {
if self.decoration.borders[0].color.alpha > 0.0 {
fills.push(Fill {
shape: Shape::Path {
contours: boundaries
.into_iter()
.map(|t| Contour::polygon(&ring_corners(rect, inner_widths, t)))
.collect(),
even_odd: true,
clip: None,
},
color: self.decoration.borders[0].color,
});
}
return fills;
}
let pattern = |side: usize| {
let next = (side + 1) % 4;
let border = self.decoration.borders[side];
let width = widths[side];
let half = width / 2.0;
let start = outer[side];
let end = outer[next];
let length = (end[0] - start[0]).abs() + (end[1] - start[1]).abs();
let tangent = [(end[0] - start[0]) / length, (end[1] - start[1]) / length];
let normal = [-tangent[1], tangent[0]];
let dotted = border.style == BorderStyle::Dotted;
let inset = if dotted { half } else { 0.0 };
let from = [
start[0] + normal[0] * half + tangent[0] * inset,
start[1] + normal[1] * half + tangent[1] * inset,
];
let end_inset = if uniform && dotted { width + half } else { 0.0 };
let to = [
end[0] + normal[0] * half - tangent[0] * end_inset,
end[1] + normal[1] * half - tangent[1] * end_inset,
];
let gap = if dotted {
dot_gap((length - width).max(0.0), width)
} else {
dash_gap(length, width)
};
Shape::Pattern {
contours: vec![Contour {
start: from,
segments: vec![Segment::Line(to)],
closed: false,
}],
width,
dash: [
if dotted {
0.0
} else {
DASH_LENGTH_WIDTHS * width
},
gap,
],
round: dotted,
clip: (!uniform).then(|| vec![outer[side], outer[next], inner[next], inner[side]]),
}
};
if uniform && self.decoration.borders[0].style == BorderStyle::Dotted {
if self.decoration.borders[0].color.alpha > 0.0 {
let mut opposite = [Vec::new(), Vec::new()];
for side in 0..4 {
if let Shape::Pattern { contours, .. } = pattern(side) {
opposite[side % 2].extend(contours);
}
}
for (side, contours) in opposite.into_iter().enumerate() {
let Shape::Pattern {
width,
dash,
round,
clip,
..
} = pattern(side)
else {
unreachable!("dotted sides are patterns")
};
fills.push(Fill {
shape: Shape::Pattern {
contours,
width,
dash,
round,
clip,
},
color: self.decoration.borders[0].color,
});
}
}
return fills;
}
let borders = self.decoration.borders;
let joined = |a: usize, b: usize| {
let bands = borders[a].bands(a);
borders[a].style == borders[b].style
&& !bands.is_empty()
&& bands == borders[b].bands(b)
};
for run in side_runs(widths, joined) {
let border = borders[run[0]];
if border.color.alpha <= 0.0 {
continue;
}
let bands = border.bands(run[0]);
if bands.is_empty() {
fills.push(Fill {
shape: pattern(run[0]),
color: border.color,
});
continue;
}
let last = run[run.len() - 1];
for band in bands {
let outer = ring_corners(rect, inner_widths, band.from);
let inner = ring_corners(rect, inner_widths, band.to);
let mut points: Vec<_> = std::iter::once(run[0])
.chain(run.iter().map(|side| (side + 1) % 4))
.map(|corner| outer[corner])
.collect();
points.extend(
std::iter::once((last + 1) % 4)
.chain(run.iter().rev().copied())
.map(|corner| inner[corner]),
);
fills.push(Fill {
shape: Shape::Path {
contours: vec![Contour::polygon(&points)],
even_odd: false,
clip: None,
},
color: band.color,
});
}
}
fills
}
}
#[cfg(test)]
mod corner_tests {
use super::*;
use kurbo::Shape as _;
fn contains(contours: &[Contour], point: Point) -> bool {
contours
.iter()
.map(|contour| {
kurbo::BezPath::from_iter(contour.path_elements())
.winding(kurbo::Point::new(f64::from(point[0]), f64::from(point[1])))
})
.sum::<i32>()
!= 0
}
fn notched_box() -> BoxPaint {
BoxPaint::whole(
Rect {
x: 0.0,
y: 0.0,
width: 80.0,
height: 60.0,
},
BoxDecoration {
radii: Arc::new(std::array::from_fn(|corner| {
std::array::from_fn(|_| {
if corner % 2 == 0 {
LengthPercentage::Percentage(0.8)
} else {
LengthPercentage::ZERO
}
})
})),
corner_shapes: Arc::new([
CornerShape::NOTCH,
CornerShape::ROUND,
CornerShape::NOTCH,
CornerShape::ROUND,
]),
borders: [Border {
width: 4.0,
style: BorderStyle::Solid,
color: Color::BLACK,
}; 4],
..Default::default()
},
)
}
#[test]
fn box_clips_share_concave_radius_constraints_and_disconnected_inner_edges() {
let paint = notched_box();
assert_eq!(
paint.radii(),
[[40.0, 30.0], [0.0; 2], [40.0, 30.0], [0.0; 2]],
"opposite notch hulls must constrain percentage radii before any consumer uses them"
);
let outer = paint.box_area(crate::paint::BoxArea::BorderBox);
let inner = paint.inner_clip([0.0; 4], [true; 2]);
assert_eq!(
outer.contours().len(),
2,
"the touching outer notches leave two islands"
);
assert_eq!(
inner.contours().len(),
2,
"inset cutouts overlap without restoring their overlap"
);
for (point, expected) in [
([60.0, 15.0], true),
([20.0, 45.0], true),
([40.0, 30.0], false),
([42.0, 15.0], false),
([60.0, 2.0], false),
] {
assert_eq!(
contains(&inner.contours(), point),
expected,
"padding clip coverage at {point:?}"
);
}
let strip = paint.inner_clip([0.0; 4], [true, false]);
assert!(
strip.outline.is_none(),
"open-axis overflow drops all corner cuts"
);
let fill = paint.border_fills();
assert_eq!(fill.len(), 1, "uniform border uses one compound ring");
let Shape::Path {
contours,
even_odd: true,
..
} = &fill[0].shape
else {
panic!("expected a filled border ring")
};
let winding = |point: Point| {
contours
.iter()
.map(|c| {
kurbo::BezPath::from_iter(c.path_elements())
.winding(kurbo::Point::new(f64::from(point[0]), f64::from(point[1])))
})
.sum::<i32>()
.abs()
% 2
== 1
};
assert!(
winding([42.0, 15.0]),
"the concave vertical border keeps its four-point thickness"
);
assert!(
!winding([60.0, 15.0]),
"padding islands are not filled by the border"
);
assert!(
!winding([20.0, 15.0]),
"the outer notch is not filled by the border"
);
}
#[test]
fn sliced_corner_clips_keep_the_assembled_geometry_and_clip_only_fragment_edges() {
let whole = notched_box();
let expected = whole.inner_clip([0.0; 4], [true; 2]);
let mut fragment = whole.clone();
fragment.background_box = Some(whole.rect);
fragment.rect.y = 10.0;
fragment.rect.height = 40.0;
fragment.first_fragment = false;
fragment.last_fragment = false;
let clip = fragment.inner_clip([0.0; 4], [true; 2]);
assert_eq!(
clip.contours(),
expected.contours(),
"fragmentation must not recompute the corner shapes from the smaller box"
);
assert_eq!(clip.reference_box, Some(expected.rect));
assert_eq!(
clip.rect,
Rect {
x: 4.0,
y: 10.0,
width: 72.0,
height: 40.0
}
);
assert_eq!(clip.bounds().clip_rect(whole.rect), clip.rect);
}
#[test]
fn corner_identity_survives_image_resolution_zoom_and_native_flows() {
use crate::style::logical::{Flow, WritingMode};
let shapes = [
CornerShape::NOTCH,
CornerShape::BEVEL,
CornerShape::ROUND,
CornerShape::SQUARE,
];
let mut style = crate::style::Style::default();
style.decoration.corner_shapes = Arc::new(shapes);
style.decoration.radii = Arc::new(std::array::from_fn(|_| {
std::array::from_fn(|_| LengthPercentage::Length(20.0))
}));
assert_eq!(
*style.decoration.with_image_type::<()>().corner_shapes,
shapes,
"image resolution must preserve dimensionless shapes"
);
style.effective_zoom = 3.0;
let used = style.used();
assert_eq!(
*used.decoration.corner_shapes, shapes,
"zoom scales radii but never the superellipse parameter"
);
assert_eq!(used.decoration.radii[0][0], LengthPercentage::Length(60.0));
for mode in [
WritingMode::HorizontalTb,
WritingMode::VerticalRl,
WritingMode::VerticalLr,
WritingMode::SidewaysRl,
WritingMode::SidewaysLr,
] {
for rtl in [false, true] {
let from = Flow {
writing_mode: mode,
rtl,
};
let to = Flow::default();
let mapped = crate::style::logical::decoration(&used.decoration, from, to);
let expected = to.corners(from, &shapes);
assert_eq!(
*mapped.corner_shapes, expected,
"{mode:?}, rtl={rtl}: shape identity follows the same corner as its radii"
);
assert_eq!(
*crate::style::logical::decoration(&mapped, to, from).corner_shapes,
shapes
);
}
}
}
#[test]
fn bevel_insets_keep_the_border_normal_offset() {
let paint: BoxPaint = BoxPaint::whole(
Rect {
x: 0.0,
y: 0.0,
width: 80.0,
height: 60.0,
},
BoxDecoration {
radii: Arc::new(std::array::from_fn(|_| {
std::array::from_fn(|_| LengthPercentage::Length(20.0))
})),
corner_shapes: Arc::new([CornerShape::BEVEL; 4]),
..Default::default()
},
);
let clip = paint.inner_clip([4.0; 4], [true; 2]);
let sum = 20.0 + 4.0 * std::f32::consts::SQRT_2;
assert!(
!contains(&clip.contours(), [10.0, sum - 11.0]),
"one point outside the offset bevel stays clipped"
);
assert!(
contains(&clip.contours(), [10.0, sum - 9.0]),
"one point inside the offset bevel survives"
);
}
}