use crate::paint::gradient::{Gradient, ResolvedGradient};
use crate::paint::{
AbsoluteColor, Border, BoxPaint, Clip, Color, LengthPercentage, POINTS_PER_PIXEL, Rect,
};
use crate::paint::{ImageInfo, NaturalDimensions};
use serde::Serialize;
use std::convert::Infallible;
use std::sync::Arc;
const SPACE_FIT_TOLERANCE: f32 = 1.0e-4;
pub(crate) const INITIAL_IMAGE_SCALE: f32 = 1.0;
const INITIAL_RESOLUTION: f32 = 1.0;
const WHOLE: f32 = 1.0;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[expect(
clippy::enum_variant_names,
reason = "variants name the CSS border-box, padding-box and content-box keywords"
)]
pub enum BoxArea {
#[default]
BorderBox,
PaddingBox,
ContentBox,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
#[expect(
clippy::enum_variant_names,
reason = "variants name the CSS repeat and no-repeat keywords"
)]
pub enum Repeat {
#[default]
Repeat,
Space,
Round,
NoRepeat,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum BackgroundClip {
Box(BoxArea),
Painted { border_area: bool, text: bool },
}
impl Default for BackgroundClip {
fn default() -> Self {
Self::Box(BoxArea::BorderBox)
}
}
impl BackgroundClip {
pub fn area(self) -> BoxArea {
match self {
Self::Box(area) => area,
Self::Painted { .. } => BoxArea::BorderBox,
}
}
pub fn text(self) -> bool {
matches!(self, Self::Painted { text: true, .. })
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
pub enum Attachment {
#[default]
Scroll,
Fixed,
Local,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum SizeComponent {
Auto,
Value(LengthPercentage),
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum BackgroundSize {
Cover,
Contain,
Explicit([SizeComponent; 2]),
}
impl Default for BackgroundSize {
fn default() -> Self {
Self::Explicit([const { SizeComponent::Auto }; 2])
}
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct PositionComponent {
pub from_end: bool,
pub offset: LengthPercentage,
}
impl PositionComponent {
pub const START: Self = Self {
from_end: false,
offset: LengthPercentage::Percentage(0.0),
};
pub const CENTER: Self = Self {
from_end: false,
offset: LengthPercentage::Percentage(0.5),
};
#[must_use]
pub fn canonical(&self) -> Self {
use crate::paint::Calculation;
let offset = Calculation::from(&self.offset);
let offset = if self.from_end {
Calculation::Sum(vec![Calculation::Percentage(1.0), offset.negate()]).simplify()
} else {
offset
};
Self {
from_end: false,
offset: Calculation::Sum(vec![
Calculation::Value(0.0),
Calculation::Percentage(0.0),
offset,
])
.into(),
}
}
pub fn resolve(&self, free: f32) -> f32 {
let offset = self.offset.resolve(free);
if self.from_end { free - offset } else { offset }
}
}
pub(crate) type Position = [PositionComponent; 2];
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub enum BackgroundImage<I = Infallible> {
None,
Url {
url: String,
resolution: Option<f32>,
scale: f32,
#[serde(skip_serializing_if = "Option::is_none")]
function: Option<ImageFunction>,
},
Image {
#[serde(skip)]
image: I,
resolution: f32,
scale: f32,
},
Gradient(Gradient),
Color(AbsoluteColor),
Invalid,
CrossFade(Vec<FadeLayer<I>>),
Element(Arc<str>),
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub struct FadeLayer<I = Infallible> {
pub image: BackgroundImage<I>,
pub percentage: f32,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub struct ImageFunction {
pub rtl: Option<bool>,
pub fallback: Option<AbsoluteColor>,
}
#[derive(Clone, Copy, Debug)]
pub enum ImageReference<'a> {
Url(ImageRequest<'a>),
Element(&'a str),
}
#[derive(Clone, Copy, Debug)]
pub struct ImageRequest<'a> {
pub url: &'a str,
pub function: Option<&'a ImageFunction>,
pub resolved: bool,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(bound(serialize = ""))]
pub struct Backgrounds<I = Infallible> {
pub images: Vec<BackgroundImage<I>>,
pub positions: [Vec<PositionComponent>; 2],
pub sizes: Vec<BackgroundSize>,
pub repeats: Vec<[Repeat; 2]>,
pub origins: Vec<BoxArea>,
pub clips: Vec<BackgroundClip>,
pub attachments: Vec<Attachment>,
pub blend_modes: Vec<crate::paint::BlendMode>,
}
impl<I> Default for Backgrounds<I> {
fn default() -> Self {
Self {
images: vec![BackgroundImage::None],
positions: [
vec![PositionComponent::START],
vec![PositionComponent::START],
],
sizes: vec![BackgroundSize::default()],
repeats: vec![[Repeat::Repeat; 2]],
origins: vec![BoxArea::PaddingBox],
clips: vec![BackgroundClip::default()],
attachments: vec![Attachment::Scroll],
blend_modes: vec![crate::paint::BlendMode::Normal],
}
}
}
pub(crate) fn cycle<T>(values: &[T], index: usize) -> &T {
&values[index % values.len()]
}
impl<I> Backgrounds<I> {
pub fn has_images(&self) -> bool {
self.images
.iter()
.any(|image| !matches!(image, BackgroundImage::None))
}
pub fn color_clip(&self) -> BackgroundClip {
*cycle(&self.clips, self.images.len() - 1)
}
pub fn clips_to_text(&self) -> bool {
self.clips.iter().any(|clip| clip.text())
}
pub fn scroll_fixed(backgrounds: &mut Arc<Self>)
where
I: Clone,
{
if backgrounds.attachments.contains(&Attachment::Fixed) {
for attachment in &mut Arc::make_mut(backgrounds).attachments {
if *attachment == Attachment::Fixed {
*attachment = Attachment::Scroll;
}
}
}
}
pub(crate) fn resolve_images<E>(
backgrounds: &mut Arc<Self>,
mut load: impl FnMut(&ImageReference<'_>) -> Result<Option<I>, E>,
) -> Result<(), E>
where
I: Clone,
{
if !backgrounds
.images
.iter()
.any(BackgroundImage::needs_loading)
{
return Ok(());
}
for image in &mut Arc::make_mut(backgrounds).images {
image.load(&mut load)?;
}
Ok(())
}
}
impl<I> BackgroundImage<I> {
pub fn is_displayable(&self) -> bool {
!matches!(self, Self::None | Self::Invalid)
}
pub fn needs_loading(&self) -> bool {
match self {
Self::Url { .. } | Self::Element(_) => true,
Self::CrossFade(layers) => layers.iter().any(|layer| layer.image.needs_loading()),
Self::None
| Self::Image { .. }
| Self::Gradient(_)
| Self::Color(_)
| Self::Invalid => false,
}
}
pub(crate) fn load<E>(
&mut self,
load: &mut impl FnMut(&ImageReference<'_>) -> Result<Option<I>, E>,
) -> Result<(), E> {
if let Self::CrossFade(layers) = self {
for layer in layers {
layer.image.load(load)?;
}
}
if let Self::Element(id) = self {
*self = match load(&ImageReference::Element(id))? {
Some(image) => Self::Image {
image,
resolution: INITIAL_RESOLUTION,
scale: INITIAL_IMAGE_SCALE,
},
None => Self::Invalid,
};
return Ok(());
}
if let Self::Url {
url,
resolution,
scale,
function,
} = self
{
let request = ImageRequest {
url,
function: function.as_ref(),
resolved: resolution.is_some(),
};
*self = match load(&ImageReference::Url(request))? {
Some(image) => Self::Image {
image,
resolution: resolution.unwrap_or(INITIAL_RESOLUTION),
scale: *scale,
},
None => function
.and_then(|function| function.fallback)
.map_or(Self::Invalid, Self::Color),
};
}
Ok(())
}
}
impl Backgrounds<Infallible> {
pub fn with_image_type<I>(&self) -> Backgrounds<I> {
Backgrounds {
images: self
.images
.iter()
.map(BackgroundImage::with_image_type)
.collect(),
positions: self.positions.clone(),
sizes: self.sizes.clone(),
repeats: self.repeats.clone(),
origins: self.origins.clone(),
clips: self.clips.clone(),
attachments: self.attachments.clone(),
blend_modes: self.blend_modes.clone(),
}
}
}
impl BackgroundImage<Infallible> {
pub fn with_image_type<I>(&self) -> BackgroundImage<I> {
match self {
Self::None => BackgroundImage::None,
Self::Url {
url,
resolution,
scale,
function,
} => BackgroundImage::Url {
url: url.clone(),
resolution: *resolution,
scale: *scale,
function: *function,
},
Self::Gradient(gradient) => BackgroundImage::Gradient(gradient.clone()),
Self::Color(color) => BackgroundImage::Color(*color),
Self::Invalid => BackgroundImage::Invalid,
Self::CrossFade(layers) => BackgroundImage::CrossFade(
layers
.iter()
.map(|layer| FadeLayer {
image: layer.image.with_image_type(),
percentage: layer.percentage,
})
.collect(),
),
Self::Element(id) => BackgroundImage::Element(id.clone()),
Self::Image { image, .. } => match *image {},
}
}
}
#[derive(Debug)]
pub struct UnresolvedImage(pub String);
impl std::fmt::Display for UnresolvedImage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "background image {} was not loaded", self.0)
}
}
impl std::error::Error for UnresolvedImage {}
pub(crate) enum Source<'a, I> {
Image(&'a I, f32, f32),
Gradient(&'a Gradient),
Color(Color),
CrossFade(Vec<(Self, f32)>, f32),
}
impl<'a, I: ImageInfo> Source<'a, I> {
pub(crate) fn of(image: &'a BackgroundImage<I>) -> Result<Option<Self>, UnresolvedImage> {
Ok(Some(match image {
BackgroundImage::None => return Ok(None),
BackgroundImage::Url { url, .. } => return Err(UnresolvedImage(url.clone())),
BackgroundImage::Element(id) => {
return Err(UnresolvedImage(format!("element(#{id})")));
}
BackgroundImage::Image {
image,
resolution,
scale,
} => Self::Image(image, *resolution, *scale),
BackgroundImage::Gradient(gradient) => Self::Gradient(gradient),
BackgroundImage::Color(color) => Self::Color(color.used()),
BackgroundImage::Invalid => Self::Color(Color::TRANSPARENT),
BackgroundImage::CrossFade(layers) => {
let percentages: Vec<f32> = layers.iter().map(|layer| layer.percentage).collect();
let (weights, leftover) = crate::paint::normalize_mix(&percentages, false);
let mut sources = Vec::with_capacity(layers.len());
for (layer, weight) in layers.iter().zip(weights) {
sources.extend(Self::of(&layer.image)?.map(|source| (source, weight)));
}
Self::CrossFade(sources, leftover)
}
}))
}
pub(crate) fn natural(&self, area: [f32; 2]) -> NaturalDimensions {
match self {
Self::Image(image, resolution, scale) => natural_points(*image, *resolution, *scale),
Self::Gradient(_) | Self::Color(_) => NaturalDimensions::default(),
Self::CrossFade(sources, leftover) => cross_fade_natural(sources, *leftover, area),
}
}
pub(crate) fn tile(&self, size: [f32; 2]) -> Option<TileImage<'a, I>> {
Some(match self {
Self::Image(image, _, scale) => TileImage::Image(image, *scale),
Self::Gradient(gradient) => TileImage::Gradient(gradient.resolve(size)?),
Self::Color(color) => TileImage::Color(*color),
Self::CrossFade(sources, leftover) => TileImage::CrossFade(
sources
.iter()
.map(|(source, weight)| Some((source.tile(size)?, *weight)))
.collect::<Option<_>>()?,
*leftover,
),
})
}
}
fn cross_fade_natural<I: ImageInfo>(
sources: &[(Source<'_, I>, f32)],
leftover: f32,
area: [f32; 2],
) -> NaturalDimensions {
if leftover >= WHOLE {
return NaturalDimensions::default();
}
let mut total = 0.0;
let mut sum = [0.0; 2];
for (source, weight) in sources {
let natural = source.natural(area);
if natural.width.is_none() && natural.height.is_none() {
continue;
}
let size = image_size(&BackgroundSize::default(), natural, area);
total += weight;
sum = [sum[0] + weight * size[0], sum[1] + weight * size[1]];
}
if total <= 0.0 {
return NaturalDimensions::default();
}
let [width, height] = sum.map(|value| value / total);
NaturalDimensions {
width: Some(width),
height: Some(height),
ratio: (height > 0.0).then_some(width / height),
}
}
#[derive(Clone, Debug)]
pub enum TileImage<'a, I = Infallible> {
Image(&'a I, f32),
Gradient(ResolvedGradient),
Color(Color),
CrossFade(Vec<(Self, f32)>, f32),
}
#[derive(Clone, Debug)]
pub struct LayerPaint<'a, I = Infallible> {
pub image: TileImage<'a, I>,
pub clip: Clip,
pub painted: BackgroundClip,
pub tile: Rect,
pub step: [f32; 2],
pub repeat: [bool; 2],
pub blend: crate::paint::BlendMode,
}
pub(crate) fn natural_points<I: ImageInfo>(
image: &I,
resolution: f32,
zoom: f32,
) -> NaturalDimensions {
let natural = image.natural_size();
let scale = if image.is_raster() {
POINTS_PER_PIXEL / resolution
} else {
POINTS_PER_PIXEL
} * zoom;
NaturalDimensions {
width: natural.width.map(|width| width * scale),
height: natural.height.map(|height| height * scale),
ratio: natural.ratio,
}
}
fn contain(area: [f32; 2], ratio: f32, cover: bool) -> [f32; 2] {
let width_limited = area[0] / ratio <= area[1];
if width_limited == cover {
[area[1] * ratio, area[1]]
} else {
[area[0], area[0] / ratio]
}
}
pub(crate) fn image_size(
size: &BackgroundSize,
natural: NaturalDimensions,
area: [f32; 2],
) -> [f32; 2] {
let NaturalDimensions {
width,
height,
ratio,
} = natural;
let resolve = |component: &SizeComponent, basis: f32| match component {
SizeComponent::Auto => None,
SizeComponent::Value(value) => Some(value.resolve(basis)),
};
match size {
BackgroundSize::Cover | BackgroundSize::Contain => ratio.map_or(area, |ratio| {
contain(area, ratio, *size == BackgroundSize::Cover)
}),
BackgroundSize::Explicit([x, y]) => match (resolve(x, area[0]), resolve(y, area[1])) {
(Some(x), Some(y)) => [x, y],
(Some(x), None) => [x, ratio.map(|r| x / r).or(height).unwrap_or(area[1])],
(None, Some(y)) => [ratio.map(|r| y * r).or(width).unwrap_or(area[0]), y],
(None, None) => match (width, height, ratio) {
(Some(x), Some(y), _) => [x, y],
(Some(x), None, Some(r)) => [x, x / r],
(None, Some(y), Some(r)) => [y * r, y],
(Some(x), None, None) => [x, area[1]],
(None, Some(y), None) => [area[0], y],
(None, None, Some(r)) => contain(area, r, false),
(None, None, None) => area,
},
},
}
}
pub(crate) fn rounded_size(
mut tile: [f32; 2],
size: &BackgroundSize,
repeat: [Repeat; 2],
area: [f32; 2],
) -> [f32; 2] {
let original = tile;
for axis in 0..2 {
if repeat[axis] == Repeat::Round && tile[axis] > 0.0 {
tile[axis] = area[axis] / (area[axis] / tile[axis]).round().max(1.0);
}
}
if let BackgroundSize::Explicit(components) = size {
for axis in 0..2 {
let other = 1 - axis;
if repeat[axis] == Repeat::Round
&& repeat[other] != Repeat::Round
&& components[other] == SizeComponent::Auto
&& original[axis] > 0.0
{
tile[other] = original[other] * tile[axis] / original[axis];
}
}
}
tile
}
fn place(
repeat: Repeat,
position: &PositionComponent,
start: f32,
area: f32,
tile: f32,
) -> (f32, f32, bool) {
if repeat == Repeat::Space {
let count = (area / tile + SPACE_FIT_TOLERANCE).floor();
if count >= 2.0 {
return (start, tile + (area - count * tile) / (count - 1.0), true);
}
}
(
start + position.resolve(area - tile),
tile,
matches!(repeat, Repeat::Repeat | Repeat::Round),
)
}
impl<I> BoxPaint<I> {
pub(super) fn fragment_padding(&self) -> [f32; 4] {
let mut padding = self.padding;
if self.assembled_box().is_some() {
return padding;
}
for (side, sliced) in padding.iter_mut().zip(self.sliced()) {
if sliced {
*side = 0.0;
}
}
padding
}
pub fn box_area(&self, area: BoxArea) -> Clip {
match area {
BoxArea::BorderBox => self.box_clip([0.0; 4], [true; 2]),
BoxArea::PaddingBox => self.inner_clip([0.0; 4], [true; 2]),
BoxArea::ContentBox => self.inner_clip(self.fragment_padding(), [true; 2]),
}
}
pub fn background_clips(&self) -> crate::paint::BoxAreas<Clip> {
crate::paint::BoxAreas {
border: self.box_area(BoxArea::BorderBox),
padding: self.box_area(BoxArea::PaddingBox),
content: self.box_area(BoxArea::ContentBox),
}
}
pub fn background_origins(&self) -> crate::paint::BoxAreas<Rect> {
crate::paint::BoxAreas {
border: self.positioning_area(BoxArea::BorderBox),
padding: self.positioning_area(BoxArea::PaddingBox),
content: self.positioning_area(BoxArea::ContentBox),
}
}
pub(crate) fn background_clip(&self, area: BoxArea) -> Clip {
self.background_geometry
.as_ref()
.map_or_else(|| self.box_area(area), |geometry| geometry.clips.area(area))
}
fn positioning_area(&self, area: BoxArea) -> Rect {
if let Some(origins) = self
.background_geometry
.as_ref()
.and_then(|geometry| geometry.origins)
{
return origins.area(area);
}
let Some(outer) = self.background_box else {
return self.box_area(area).rect;
};
let borders = self.decoration.borders.map(Border::used_width);
let insets: [f32; 4] = match area {
BoxArea::BorderBox => [0.0; 4],
BoxArea::PaddingBox => borders,
BoxArea::ContentBox => std::array::from_fn(|side| borders[side] + self.padding[side]),
};
Rect {
x: outer.x + insets[3],
y: outer.y + insets[0],
width: outer.width - insets[1] - insets[3],
height: outer.height - insets[0] - insets[2],
}
}
}
impl<I: ImageInfo> BoxPaint<I> {
pub fn background_layers(
&self,
page_area: Rect,
) -> Result<Vec<LayerPaint<'_, I>>, UnresolvedImage> {
if !self.draw_background {
return Ok(Vec::new());
}
Ok(self
.layers(&self.decoration.backgrounds, page_area)?
.into_iter()
.map(|(_, layer)| layer)
.collect())
}
pub fn mask_layers(
&self,
page_area: Rect,
) -> Result<Vec<(usize, LayerPaint<'_, I>)>, UnresolvedImage> {
self.layers(&self.decoration.masks.layers, page_area)
}
fn layers<'a>(
&'a self,
backgrounds: &'a Backgrounds<I>,
page_area: Rect,
) -> Result<Vec<(usize, LayerPaint<'a, I>)>, UnresolvedImage> {
let page_area = self
.background_geometry
.as_ref()
.and_then(|geometry| geometry.viewport)
.unwrap_or(page_area);
place_layers(
backgrounds,
|index| {
if *cycle(&backgrounds.attachments, index) == Attachment::Fixed {
page_area
} else {
self.positioning_area(*cycle(&backgrounds.origins, index))
}
},
|index| self.background_clip(cycle(&backgrounds.clips, index).area()),
)
}
}
pub(crate) fn place_layers<I: ImageInfo>(
backgrounds: &Backgrounds<I>,
area: impl Fn(usize) -> Rect,
clip: impl Fn(usize) -> Clip,
) -> Result<Vec<(usize, LayerPaint<'_, I>)>, UnresolvedImage> {
let mut layers = Vec::new();
for (index, image) in backgrounds.images.iter().enumerate().rev() {
let Some(source) = Source::of(image)? else {
continue;
};
let area = area(index);
let extent = [area.width, area.height];
let natural = source.natural(extent);
let size = cycle(&backgrounds.sizes, index);
let repeat = *cycle(&backgrounds.repeats, index);
let tile = rounded_size(image_size(size, natural, extent), size, repeat, extent);
if !(tile[0] > 0.0 && tile[1] > 0.0 && tile.iter().all(|v| v.is_finite())) {
continue;
}
let [position_x, position_y] = &backgrounds.positions;
let (x, step_x, repeat_x) = place(
repeat[0],
cycle(position_x, index),
area.x,
extent[0],
tile[0],
);
let (y, step_y, repeat_y) = place(
repeat[1],
cycle(position_y, index),
area.y,
extent[1],
tile[1],
);
let Some(image) = source.tile(tile) else {
continue;
};
layers.push((
index,
LayerPaint {
image,
clip: clip(index),
painted: *cycle(&backgrounds.clips, index),
tile: Rect {
x,
y,
width: tile[0],
height: tile[1],
},
step: [step_x, step_y],
repeat: [repeat_x, repeat_y],
blend: *cycle(&backgrounds.blend_modes, index),
},
));
}
Ok(layers)
}